В этой статье мы настроим 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 [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 туннеле, запуска скриптов и других задачах автоматизации.
The Secure Shell Protocol (SSH) allows one to remotely access a terminal interface on a remote machine. In addition, it allows for capabilities such as port tunneling1, file transfers and screen forwarding.
The main reasons for setting up SSH access on my machine were to allow me to:
- Access the filesystem remotely and transfer files
- Develop on VSCode remotely, in Remote-Containers
- Tunnel ports to/from the remote machine (e.g., to access local applications only listening on
localhost
)
SSH Authentication Methods
SSH supports several authentication methods, but the most common are:
password
: Login using the password of the host user. Most common, but vulnerable to password guessing attacks such as brute-force or dictionary-based methods.publickey
: Utilizes public key authentication. Effectively resistant2 to any form of password guessing attack. This mode also allows for the use of certificates, and is the mode we will be using.
Certificates
What are certificates?
Public key (aka asymmetric) encryption consists of a pair of keys — the private and public key. Any information encrypted with the public key can only be decrypted by the corresponding private key (and vice-versa). Public keys are shared publicly as the name suggests, while the private key is kept secret.
This can be used to create a digital signature, an electronic variant of the handwritten signature, with similar properties:
- Authentication: Proves that a message was sent by the signer and no one else.
- Non-repudiation: Someone who has signed a message, cannot later deny they have done so.
In addition, a digital signature offers another property which handwritten signatures lack:
- Integrity: Any alteration to the signed message renders the signature invalid.
This brings us to the topic of certificates (public key certificates). These are electronic documents which prove that the owner’s public key has been verified by some authority (the certificate issuer). This lets us trust the public keys of unknown entities, provided we trust the certificate issuer. In fact, this is how website certificates are issued under TLS, the cryptographic protocol powering HTTPS.
SSH Certificates
SSH certificates are essentially public SSH keys signed by some authority’s private key, and allow the host to authenticate clients. When a client tries to connect to an SSH host, the client proves its identity by showing the host its public key certificate, which is signed by an authority the host trusts. Unlike TLS however, there are no authorities trusted by default (aka root certificate authorities). The trusted certificate authority on the host must be set by the user.
An advantage of using certificates is that all clients with public keys signed by an authority trusted by the host are automatically granted access, and there is no need to add or maintain the client’s public keys in the authorized_keys
file on the host.
1. Setting up SSH on the host
First, ensure that OpenSSH, the open-source implementation of the SSH protocol and its tools, is installed.
To check that sshd
, the SSH daemon, is running on the host, open a Powershell terminal as an administrator and execute Get-Service sshd
. The output should be similar to the following:
Status Name DisplayName
------ ---- -----------
Running sshd OpenSSH SSH Server
Next, we will use ssh-keygen
to generate our server’s public-private key pair, which will be used to sign the public keys of clients we want to allow SSH access from. This keypair is different from the host’s keypair (the keypair presented to clients), which is usually stored in %ProgramData%\ssh\sshd_config
.
Open a terminal and type the following:
ssh-keygen -f user_ca -t ed25519
-f
: the name of the keypair-t
: the key algorithm, in this case EdDSA with Curve25519
The passphrase is used to encrypt the private key, and is optional. You should get the following output:
Generating public/private ed25519 key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in user_ca.
Your public key has been saved in user_ca.pub.
The key fingerprint is:
SHA256:OxXXnTRmRiD7bxGMgyuU4fz4JTxKcEpGrngbIWpz/ow nick@Desktop-Nick
The key's randomart image is:
+--[ED25519 256]--+
| . . . .oB |
| o o o +.B.o|
| . . = *.o.o.+.|
| . o = = +oo . .|
| + o + .S+.* o . |
|. + . o .o+ + . .|
| . . o. . o |
| + . . |
| E o |
+----[SHA256]-----+
user_ca
contains the private key of this pair, and must be kept secret.
Now, we need to tell our host to trust this public key, and enable public key authentication.
Open up C:\ProgramData\ssh\sshd_config
and make the following changes:
- Set
PubkeyAuthentication
toyes
- Set
TrustedUserCAKeys
to the location of theuser_ca.pub
file generated above (note, use the full path to eliminate ambiguity) - (optional but recommended) Disable password authentication: set
PasswordAuthentication
tono
Now, the host is ready to accept connections from clients whose public keys were signed by this private key (user_ca
above).
2. Signing a client’s SSH public key
We’ll now sign a client’s public key, using ssh-keygen
. To make things a bit simpler, we’ll generate the client’s keypair on the host, sign it, and then return the signed keypair to the client.
First, we generate a keypair on the host:
ssh-keygen -f client_key -t ed25519
Next, we use ssh-keygen
to sign the client’s public key (client_key.pub
), with the private key of the keypair we generated earlier (user_ca
). (Note: if you have added the private key to ssh-agent
, see below.
ssh-keygen -s user_ca -I <client_name> -n <usernames> -V +1d client_key.pub
If you get an error about the public key not being found, use the absolute path to the user_ca.pub
file instead, or ensure you run the command from the same directory as the user_ca.pub
file.
-s
: Indicates we want to sign a public key, with the provided private key.-I
: Key identifier, usually the name of the client. Will appear in logs.-n
: Comma-separated list of usernames (on the host, not WSL) which the client is allowed to log into the host as. Usernames must already exist on the host. Also known as ‘principals’. If this option is omitted, the client will not be able to login.-V
: Validity interval of the certificate. If omitted, the certificate will be valid forever.
Then, copy the files client_key
(private key), client_key.pub
(public key) and client_key-cert.pub
(signed public key) to the client 4. Usually, these files are placed in %UserProfile%\.ssh
.
3. Login
Now, test the SSH login from the client!
ssh -i <PATH_TO_KEYFILE> you@your.domain.name
where <PATH_TO_KEYFILE>
is the location to the private key, e.g. ~\.ssh\client_key
.
You should not be prompted for a password.
If you don’t want to keep having to specify the keyfile, create/edit the config file (usually at ~/.ssh/config
)5:
Host ssh.your-domain.com
HostName ssh.your-domain.com
User your-username
IdentityFile ~/.ssh/your_private_key
(Optional) Adding the private key and signed public key to ssh-agent
ssh-agent
is a program which is able to store private keys and the signed public key using the appropriate secure credential storage for the operating system. This presents a more secure alternative than storing the private key unencrypted on the server.
In order to add keys to the agent, use ssh-add
:
ssh-add <keyfile>
<keyfile>
is the location of the private key, e.g. user_ca
.
To check the keys which have been added to the agent, run ssh-add -l
.
From now on, ssh-agent
will automatically supply the signed public key and private key in commands such as ssh
.6
(Only on Windows)
Note: (On the host) If you added the host’s certificate signing private key (e.g. user_ca
) to ssh-agent
, when you want to sign a client`s public key, you need to use the following command instead:
ssh-keygen -Us user_ca -I <client_name> -n <usernames> -V +1d client_key.pub
-U
indicates the private key should be extracted from ssh-agent
.
(Optional) Host Public Key Verification over DNS
How does the client authenticate the host the first time round? How does the client know that the public key the host is presenting really is the correct key, and not an attacker’s key?
One way would be to verify the host’s key fingerprint manually when connecting the first time. This is known as trust on first use.
# ssh server@server.com
The authenticity of host 'server@server.com (192.168.65.2)' can't be established.
ECDSA key fingerprint is SHA256:e3eMAe6IrkZkWfCnYasBJUNRyHDC8SzDI0gLP9wWf1A.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
However, it’s not easy to remember.
A better way is to add the host key to the DNS record, in a special type of record called SSHFP.
We can get the required information to add via ssh-keygen
:
C:\WINDOWS\system32>ssh-keygen -r your.domain.name
your.domain.name IN SSHFP 4 1 3e35102ba1ef8777b74d257edcef0d6391cb9c19
your.domain.name IN SSHFP 4 2 f9212b988c5cb2e9027746b13339c6b32d9f1c49183620765476ba76b51ddd31
You need to add this information as an SSHFP
record via your DNS registrar.
Finally, on the client, when we connect, we use the following command (non case-sensitive):
ssh -o "VerifyHostKeyDNS ask" you@your.domain.name
The authenticity of host 'your.domain.name (xx.xx.xx.xx)' can't be established.
ED25519 key fingerprint is SHA256:+SErmIxcsukCd0axMznGsy2fHEkYNiB2VHa6drUd3TE.
Matching host key fingerprint found in DNS.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
Sadly, the OpenSSH client in Windows does not support VerifyHostKeyDNS
.
Why not host your own SSH-CA?
Prior to my decision to use ssh-keygen
as the certificate authority, I considered a number of alternative self-hosted SSH certificate authorities, but rejected them as follows:
- Bastillion — Not certificate based. Also, need to manually upload and download the public keys and configure SSH.
- Cloudflare Tunnel — Need to download on both server and client. I had some issues setting up SSH certificate login.
- Step — Need to download on both server and client. Also, TLS connection to
step-ca
from a client requires adding its generated root certificate as a trusted certificate3. - Teleport — Need to download on both server and client. Teleport Nodes (the server component) are not supported on Windows. The ability to record SSH sessions might be useful if I were to move to Linux.
- Vault by HashiCorp — Need to download on both server and client.
Instead, to streamline the process of generating client certificates, I plan to write a certificate provisioning server which will probably rely on the (already-existing) 2FA login my web app backend uses. This would call ssh-keygen
and return the signed public/private key pair.
*[nonce]: Number Only used oNCE
Usually you will need a pair of SSH username and password to connect to a remote server. But there’s also another way to connect to the server via SSH but without password, just using a dot pem (example.pem) file.
Here’s how we usually do on Windows
1. Let’s SSH login using pem to confirm if it’s throwing error or the pem is fine, if error then we need to move to step 2 to fix it:
ssh adam@10.0.0.123 -i server-cert.pem
And here’s the usual error that will throw if your pem file is not ready for SSH login.
You need to follow the next step to make your pem certificate ready to login to your server via SSH.
2. Open Windows Explorer, then right-click on the pem file, then select «Properties». Navigate to the «Security» tab, and click «Advanced»
4. Delete all permissions, so it doesn’t have any permission
5. Now add you as the only only owner. By click button Add and then Select a principal, then Advanced.
6. On the showing pop up, click Find now, then will show you list of users, select only you and click OK
7. On the basic permissions select full control, so all the permissions is checked
8. Then click Apply and OK
Now you can login SSH using pem certificate and without using password. You don’t need to repeat the process unless you move the pem file.
A Pem file is a container format that may just include the public certificate or the entire certificate chain (private key, public key, root certificates): Private Key. Server Certificate (crt, public key) (optional) Intermediate CA and/or bundles if signed by a 3rd party.
В настоящей статье описан алгоритм настройки SSH-клиента Putty для ОС Windows для работы с JaCarta PKI.
JaCarta PKI – токены производства компании «Аладдин Р.Д.» для строгой двухфакторной аутентификации пользователей при доступе к защищённым информационным ресурсам предприятия, безопасного хранения ключей и ключевых контейнеров программных СКЗИ.
Общие сведения
SSH
SSH — сетевой протокол прикладного уровня, позволяющий производить удалённое управление операционной системой и туннелирование TCP-соединений. Шифрует весь трафик, включая и передаваемые пароли. SSH допускает выбор различных алгоритмов шифрования. SSH-клиенты и SSH-серверы доступны для большинства сетевых операционных систем.
SSH поддерживает возможность аутентификации по RSA-ключу, что обеспечивает максимальный уровень безопасности для канала передачи данных, а также двухфакторную аутентификацию удалённых пользователей.
Аутентификация по сертификату
Для настройки работы SSH по RSA-сертификатам необходимо настроить SSH-сервер, а также SSH-клиента на клиентской машине. В данном документе описан алгоритм настройки работы SSH с использованием смарт-карты, либо токена JaCarta PKI для целей аутентификации и шифрования установленного канала.
Настройка смарт-карт для SSH-клиента
Порядок настройки серверной части на примере Ubuntu
Генерация ключевой пары утилитой ssh-keygen
- Перейти в директорию /home/user/.ssh
- ssh-keygen -t rsa
- Задать имя ключа, например, key
- Задать пароль ключа (для шифрования закрытого ключа), например, 12345678
- На выходе получаем два файла, например, key и key.pub
Генерация запроса на сертификат с ключами из п. 1
- openssl req -new -out user.req -key key
Выпуск сертификата в CA openssl
- Настройка openssl CA
- cd /etc/ssl
- sudo -i
- echo “01” > serial
- cp /dev/null index.txt
- Редактируем /etc/ssl/openssl.cnf nano openssl.cnf
- dir = ./
- certs = $dir/certs
- crl_dir = $dir/crl
- database = $dir/index.txt
- new_certs_dir = $dir/certs
- certificate = $dir/ca.crt
- serial = $dir/serial
- crl = $dir/crl.pem
- private_key = $dir/ca.key
- openssl req -new -x509 -keyout ca.key -out ca.crt -days 3650
- mkdir crl
- Скачать
- Запуск makehashlink
- chmod +x make_hash_link.sh
- ./make_hash_link.sh /etc/ssl
- ./make_hash_link.sh /etc/ssl/crl
- Подписание сертификата пользователя (выпуск)
- sudo -i
- cd /home/user/.ssh
- openssl ca -out user.crt -infiles user.req
Импорт открытого ключа в Autorized_keys
- В директории /home/user/.ssh должен находиться файл открытого ключа, содержащий ssh-rsa {KEY}. В примере мы создали файл с именем key.pub
- Импортируем данный ключ в файл authorized_keys
- echo key.pub > authorized_keys
Донастройка серверной части
- chmod 700 authorized_keys
- Настройки openssh. В /etc/ssh/sshd.conf редактируем конфигурацию аутентификации
- RSAAuthentication yes
- PubkeyAuthentication yes
- PasswordAuthentication no — отказ от аутентификации по паролю (опционально)
Запись сертификата на смарт-карту
Необходимо перенести сертификат на смарт-карту. Для переноса необходимо собрать все необходимые объекты в зашифрованный контейнер и записать его на смарт-карту.
- openssl pkcs12 -export -in user.crt -inkey key -certfile ca.crt -name «user» -out user.pfx
- Перенос файла user.pfx на Windows систему с установленным ПО «Единый Клиент JaCarta», либо JC Client
- Ввод PIN-кода пользователя
- Импортировать сертификат на токен
- Выбрать файл user.pfx и нажать «Импорт»
Проверка работоспособности сертификата
ssh -I /usr/lib/x86-athena/libASEP11.so 127.0.0.1
Настройка SSH-клиента Putty на ОС Windows
Запуск утилит из дистрибутива putty-cac\executables
- pageant.exe
- putty.exe
Для работы требуется версия putty-cac 0.62
Выбор сертификата в pageant
В общем случае сертификат появляется в хранилище сертификатов автоматически, но в некоторых случаях может потребоваться его добавление вручную.
Запуск и настройка Putty
Вкладка Connection/SSH/CAPI
Вход в сессию SSH по сертификату
После ввода PIN-кода пользователя будет установлена сессия SSH.
The Secure Shell (SSH) protocol and the OpenSSH project have been around for decades on Linux. But OpenSSH on Windows hasn’t been embraced in the Windows world until recently. As such, a Windows Server doesn’t typically come pre-built and ready to go and requires some setup.
Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.
In this tutorial, you’re going to learn how to SSH into your Windows Server just as easily as Linux. You’ll learn how to get OpenSSH installed (or updated) on Windows, add appropriate firewall rules, and configure public key, password, and certificate-based authentication.
Prerequisites
To effectively follow the examples and demos in this article, you’ll need to meet these requirements below.
- A Windows Server machine – This article will use Windows Server 2019 Datacenter. The server this tutorial will use will have a user account called june and will connect to the server at the IP address of 40.117.77.227 with a hostname of ataWindows.
- A local computer with PowerShell 7.1 installed. PowerShell 7.1 is available in Windows, Linux, and macOS. The examples in this article use PowerShell 7.1 in Windows 10.
Downloading OpenSSH
Unlike Linux servers, Windows servers do not have an out-of-the-box SSH server running. But Microsoft has released an open-source port of OpenSSH for Windows. With this release, you can now set up an SSH server on a Windows machine.
To get started, you’ll first need to download OpenSSH. To do so, follow the steps below:
- Connect to the desktop on a Windows Server using Remote Desktop (RDP) or your preferred desktop manager client.
2. On your Windows Server desktop, open an elevated Windows PowerShell console.
3. Next, copy the code below, paste it in the PowerShell window, and press Enter. This script will download the latest OpenSSH release, which as of this writing, is v8.1.0.0p1-Beta to the current working directory.
If you like to save the PowerShell code to download OpenSSH, you can also open a code editor like Windows PowerShell ISE or Visual Studio Code and save it in there.
## Set network connection protocol to TLS 1.2
## Define the OpenSSH latest release url
$url = 'https://github.com/PowerShell/Win32-OpenSSH/releases/latest/'
## Create a web request to retrieve the latest release download link
$request = [System.Net.WebRequest]::Create($url)
$request.AllowAutoRedirect=$false
$response=$request.GetResponse()
$source = $([String]$response.GetResponseHeader("Location")).Replace('tag','download') + '/OpenSSH-Win64.zip'
## Download the latest OpenSSH for Windows package to the current working directory
$webClient = [System.Net.WebClient]::new()
$webClient.DownloadFile($source, (Get-Location).Path + '\OpenSSH-Win64.zip')
4. The OpenSSH-Win64.zip file should now be in your current working directory. Verify this by running the command below.
As you can see below, the OpenSSH-Win64.zip file exists in the directory.
Installing OpenSSH
After you’ve downloaded OpenSSH-Win64.zip, the next step is to install OpenSSH on the server. There’s no installation wizard in case you’re expecting it.
- While still in the same PowerShell session, copy the code below and run it in PowerShell. This code extracts the OpenSSH-Win64.zip file contents to C:\Program Files\OpenSSH.
# Extract the ZIP to a temporary location
Expand-Archive -Path .\OpenSSH-Win64.zip -DestinationPath ($env:temp) -Force
# Move the extracted ZIP contents from the temporary location to C:\Program Files\OpenSSH\
Move-Item "$($env:temp)\OpenSSH-Win64" -Destination "C:\Program Files\OpenSSH\" -Force
# Unblock the files in C:\Program Files\OpenSSH\
Get-ChildItem -Path "C:\Program Files\OpenSSH\" | Unblock-File
2. After extracting the ZIP file, run the command below in PowerShell to execute the script C:\Program Files\OpenSSH\install-sshd.ps1. This script installs the OpenSSH SSH Server service (sshd) and OpenSSH Authentication Agent service (sshd-agent).
& 'C:\Program Files\OpenSSH\install-sshd.ps1'
You can see the expected result below.
To ensure that the SSH server starts automatically, run the command below in PowerShell.
## changes the sshd service's startup type from manual to automatic.
Set-Service sshd -StartupType Automatic
## starts the sshd service.
Start-Service sshd
Adding a Windows Firewall Rule to Allow SSH Traffic
This procedure is applicable only if your Windows Server is using the Windows Firewall. For servers using third-party firewalls, refer to your firewall documentation on how to allow port 22.
Installing OpenSSH does not automatically create a firewall exception rule to allow SSH traffic. Therefore, your next task is to create the firewall rule manually.
One of the easiest ways to create a new Windows Firewall rule is with PowerShell and the New-NetFirewallRule
cmdlet. The command below creates a firewall rule called Allow SSH that allows all inbound TCP traffic destined to port 22.
Copy the command below and run it in PowerShell.
New-NetFirewallRule -Name sshd -DisplayName 'Allow SSH' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
The below screenshot shows the expected output in PowerShell after creating the firewall rule.
Connecting with SSH using Password Authentication
At this point, you’ve installed OpenSSH on Windows and performed the initial server configuration. The next step is to test whether connecting via SSH actually works.
To test your newly configured SSH server, let’s now run the ssh
command on your local computer.
The same steps in this section also apply when connecting to a Linux SSH server.
1. From your local computer this time, open PowerShell.
2. Next, run the command below to start the SSH login process. Make sure to change the username and the remote host of your Windows Server.
3. Since you’re connecting for the first time to the server, you will see a prompt saying that the authenticity of the host can’t be established. The message means that your computer does not recognize the remote host yet. Type yes and press Enter to continue.
4. When prompted for the password, type in your account password and press enter.
5. After logging in, as you can see in the screenshot below, you’ll arrive at the remote host’s command prompt. Suppose you want to confirm that you’ve entered the session on the remote host. To do so, type hostname
, and press Enter. The command should return the remote computer name.
Changing the Default Shell for OpenSSH to PowerShell
When you first logged in to your Windows SSH server, you’ll notice that the default shell or command interpreter is CMD. Having CMD as the default SSH shell is fine, but if you prefer to use PowerShell as the default shell instead, follow these steps.
To change the default OpenSSH shell from CMD to PowerShell:
First, open an elevated PowerShell window on your Windows Server, if you don’t have one open already.
Next, create a new registry string value called DefaultShell in the registry key HKLM:\SOFTWARE\OpenSSH. Set the DefaultShell string data to the Windows PowerShell path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
The screenshot below shows the expected result of the command.
Configuring Public Key Authentication
In the previous sections, you connected with a username and password. this works but a more secure way to authenticate with an SSH server is by using a key pair.
In a nutshell, a key pair consists of two keys called the public key and private key, which constitute a set of security credentials to prove your identity.
The public key is stored on the server, while the private key stays on the local computer. You must treat a private key like your password. If the private key is compromised, anyone can use it to gain access to your SSH server.
Public keys have to be on the server. But where? For OpenSSH on Windows, the SSH server reads the public keys from the C:\ProgramData\ssh\administrators_authorized_keys file. But this file does not exist by default. You must create one first.
Follow these steps below to create the administrators_authorized_keys file and set its proper access control list (ACL).
On the Windows Server:
1. Open an elevated Windows PowerShell console if not already.
2. Copy the command below and run it in PowerShell. This command creates the administrators_authorized_keys file using the New-Item
cmdlet.
New-Item -Type File -Path C:\ProgramData\ssh\administrators_authorized_keys
You should see a result similar to the screenshot below.
3. Next, get the ACL currently assigned to the ssh_host_dsa_key file and copy that ACL to the administrators_authorized_keys file. To do so, run the command below.
get-acl C:\ProgramData\ssh\ssh_host_dsa_key | set-acl C:\ProgramData\ssh\administrators_authorized_keys
The OpenSSH service requires that only the Administrators group and the SYSTEM account have access to the administrators_authorized_keys file. And copying the ACL of ssh_host_dsa_key to administrators_authorized_keys makes sense because the ACL is already set.
4. Now open up Windows Explorer.
5. Navigate to the C:\ProgramData\ssh\ folder.
6. Right-click on the administrators_authorized_keys file and click Properties.
7. On the properties page, click on the Security Tab and click Advanced.
8. Then, confirm if the permissions are as shown like in the image below.
Generating a New SSH Key Pair
To generate a new SSH key pair, use the ssh-keygen
command, which is part of the OpenSSH client tools built-in to Windows 10 (and above) and most Linux operating systems.
The example shown in this section works on both Windows and Linux computers.
On your local computer, in a PowerShell console:
1. Navigate to your home folder’s .ssh directory by running the command below.
2. Next, type in the command ssh-keygen
and press Enter. When asked to enter a file location to save the key you’re generating, keep the default location and press Enter. Doing so allows your SSH client to find your SSH keys when authenticating automatically.
In Windows, the default key file is C:\Users\<username>\.ssh\id_rsa.
3. At the next prompt, leave the passphrase blank. At this point, you do not have to use a passphrase for testing.
Adding a passphrase to your private key significantly increases its security. A passphrase acts as a second-factor authentication (2FA) to your private key.
You’ll notice that the command created two files; id_rsa (private key) and id_rsa.pub (public key).
Deploying the Public Key to the Windows SSH Server
Now that you’ve generated your private-public key pair, your next step is to copy the public key to the C:\ProgramData\ssh\administrators_authorized_keys file on the SSH server.
On your local computer, in a PowerShell console:
1. Copy the code below and run it in PowerShell. Make sure to change the username and IP address first. You can refer to the comment above each command to know what each command does.
# Read the public key
$public_key = Get-Content ~/.ssh/id_rsa.pub
# Append the public key to the administrators_authorized_keys on the server using ssh.
ssh [email protected] "'$($public_key)' | Out-File C:\ProgramData\ssh\administrators_authorized_keys -Encoding UTF8 -Append"
2. Enter your password when prompted, and ssh will proceed to copy the public key. You will see a similar result, as shown below.
Connecting with SSH using Public Key Authentication
Now that you’ve copied your public key to your SSH server, you no longer need to use a password to authenticate. As you can see below, ssh did not prompt for a password.
Configuring Certificate Authentication
Like public key authentication, certificate authentication is passwordless or passphrase-protected. To enable certificate login, follow the same procedure of generating a key pair sans deploying the public key to the SSH server.
You do not need to map the public key to the authorized_keys or administrators_authorized_keys files on the SSH server. Instead, the public key is signed using a certificate authority (CA) key.
Creating the Certificate Authority (CA) Key
Generating the CA keys for signing is similar to generating a user key pair that you did earlier in this article. Only this time, you’ll need to specify a filename for the new CA keys. To do so, on your Windows Server in a PowerShell console:
Execute the ssh-keygen
command as shown below. This command creates the CA key in C:\ProgramData\ssh\ca_userkeys, but feel free to use a different file name. Using a different filename will not affect the CA key functionality.
When asked for a passphrase, leave the passphrase empty and press Enter.
ssh-keygen -f C:\ProgramData\ssh\ca_userkeys
You can see below that the command created two files. ca_userkeys, which is the private key, and ca_userkeys.pub, which is the public key.
Now that you’ve generated the CA keys, tell the SSH server to trust the CA and where to find the CA key. To do this, add a new line TrustedUserCAKeys path/to/ca_userkeys.pub
to the C:\ProgramData\ssh\sshd_config file on the server.
Run the commands below to append the configuration item in the file sshd_config.
# If the SSH server is Windows
echo TrustedUserCAKeys C:\ProgramData\ssh\ca_userkeys.pub>> C:\ProgramData\ssh\sshd_config
Signing the User’s Public Key
At this point, you’ve generated the CA keys and configured the SSH server to trust the CA public key file. What’s left now is to sign your user public key.
On your local computer, in a PowerShell console:
1. Copy the id_rsa.pub
file to your home drive on the SSH server using the SCP command. Make sure to change the username and IP address to the correct values.
2. Log in to your Windows Server using ssh. Once logged in, run ssh-keygen
to sign the user’s public key. You’ll notice that the command below used several parameters. Let’s break them down.
-s C:\ProgramData\ssh\ca_userkeys
– specify the CA key’s location for signing the public key. In this example, the CA key is the one you generated.-I id_username
– specify the ID you want to assign to the signed user public key. Change theid_username
value to any name you want.-V +4w
– this parameter specifies the validity period for the signed key. In this example,+4w
means that the signed user key will be valid for four weeks. You can change this value to your preferred validity period.-n username
– this is the username of whom will own the signed public key.<path to id_rsa.pub>
– this is the user public key’s location to sign (Windows).
ssh-keygen -s C:\ProgramData\ssh\ca_userkeys -I id_username -V +4w -n username ~/id_rsa.pub
After you run the command in your SSH session, you should get a similar output, as shown below. As you can see, the command generated a new file called id_rsa-cert.pub, which is the signed user certificate.
3. Now, navigate back to your local computer PowerShell session and copy the id_rsa-cert.pub file from the server to your local computer. Change the username and IP address to the correct values first before running the command.
After the copy completes, you’ll find the signed user certificate in your home folder, as shown below.
Connecting with SSH using Certificate Authentication
You’ve configured certificate authentication, and now you have your user certificate. You should now test if you can connect the SSH server with certificate authentication.
The command to connect to SSH with a certificate is the same as using a password or public key. But, if you enabled public key authentication previously, disable it first. Otherwise, ssh will keep using your key pair instead of your certificate.
To disable your key-pair, remove your public key from the administrators_authorized_keys file. To do so, follow these steps.
Note that the succeeding commands will empty the whole administrators_authorized_keys file, effectively removing all mapped public keys. If you don’t want to clear all mapped public keys, use a text editor to remove selected public keys from each file manually.
While SSHed into the Windows Server:
1. Run the below code in PowerShell to empty the administrators_authorized_keys file.
# Clear the administrators_authorized_keys file
$NULL > C:\ProgramData\ssh\administrators_authorized_keys
# Confirm that the administrators_authorized_keys is empty
Get-Content C:\ProgramData\ssh\administrators_authorized_keys
2. At this point, the authorized_keys and administrators_authorized_keys files are empty, as you can see in the screenshot below.
3. Type exit
and press Enter to disconnect from your SSH session. You’ll be back to your PowerShell session.
4. After removing the public keys, your next ssh login attempt will use certificate authentication. The login experience will be the same as public key authentication.
Conclusion
You’ve now set up an OpenSSH Windows Server from scratch all the way to exploring and setting up various authentication means. You can now connect to your Windows Servers exactly how you would with Linux!