В этой статье мы настроим 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 туннеле, запуска скриптов и других задачах автоматизации.
Authors: | Created: 2023-07-05 | Last update: 2023-07-05
Windows SSH Client with ed25519 Keys for Secure Connections¶
In the modern digital age, ensuring the security of your connections is critical. This guide will walk you through the steps to configure the SSH client and SSH agent on Windows using ed25519 keys, allowing for secure connections to services like Git and remote servers.
Introduction to SSH and ed25519 Keys¶
SSH, or Secure Shell, is a cryptographic network protocol for secure communication over an unsecured network. It is particularly used for secure logins, file transfers, and command-line operations.
ed25519 is a public-key signature system that is renowned for high security with relatively short key lengths. This makes it faster and more efficient compared to older algorithms such as RSA.
OpenSSH Client Installation¶
To utilize SSH, you need to ensure that the OpenSSH client is installed on your Windows system.
Note
The above below should be performed in PowerShell with Administrator privileges.
- Check if OpenSSH Client is available by running the following cmdlet:
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
If OpenSSH Client is not installed, the output will be:
Name: OpenSSH.Client~~~~0.0.1.0
State: NotPresent
If it’s not present, proceed to the next step to install it.
- Install the OpenSSH Client by running the following command:
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
The command should return:
Path:
Online: True
RestartNeeded: False
Setting Up SSH Agent in Windows¶
The SSH Agent is a background service that stores your keys. When connecting to a remote host using SSH, the agent can automatically provide the key.
Note
The above below should be performed in PowerShell with Administrator privileges.
- Set SSH Agent to start automatically at boot:
Set-Service -Name ssh-agent -StartupType 'Automatic'
- Start the SSH Agent service:
Start-Service -Name ssh-agent
- Test the SSH Agent Is Running:
Get-Service -Name ssh-agent
The output should be:
Status Name DisplayName
------ ---- -----------
Running ssh-agent OpenSSH Authentication Agent
Generating and Adding ed25519 SSH Keys¶
Note
The above below should be performed in PowerShell with regular user privileges.
- Generate ed25519 SSH keys:
ssh-keygen -t ed25519 -C "your_email@example.com"
This command generates an ed25519 key pair. The default location for the keys is C:\Users\<YourUsername>\.ssh. The private key is named id_ed25519 and the public key is named id_ed25519.pub.
- Adding the ed25519 SSH Key to the SSH Agent:
ssh-add $env:USERPROFILE\.ssh\id_ed25519
If your keys are stored in a different location or have a different name, you can specify the full path to the key file as an argument to ssh-add. For example:
ssh-add C:\path\to\your\private-key-file
Importing Existing ed25519 SSH Keys (Optional)¶
If you already have an existing pair of ed25519 SSH keys that you would like to use, you can import them into your SSH Agent.
Note
The above below should be performed in PowerShell with regular user privileges.
-
Copy your existing private key to the default SSH folder. The default folder for SSH keys is typically
C:\Users\<YourUsername>\.ssh. Make sure the private key file you are copying is namedid_ed25519. -
Add the existing ed25519 SSH Key to the SSH Agent:
ssh-add $env:USERPROFILE\.ssh\id_ed25519
Note: If your private key file is located in a different path or has a different name, you can specify the full path to the key file as an argument to ssh-add. For example:
ssh-add C:\path\to\your\private-key-file
- Copy your existing public key to the servers or services you want to connect to. This typically involves appending the contents of your public key file to the
~/.ssh/authorized_keysfile on the server.
Step 5: Using SSH with ed25519 Keys for Secure Connections¶
Now that you have your ed25519 SSH keys generated or imported, and added to the SSH Agent, you can use SSH to connect to remote servers or services like Git securely.
For example, to connect to a remote server:
Using SSH keys will also allow you to interact with Git repositories securely, which is especially helpful when dealing with private repositories or pushing code changes.
Wrapping Up¶
By following this guide, you have configured the SSH client and SSH agent on your Windows system using ed25519 keys. This configuration ensures secure communication with services like Git and remote servers, safeguarding the integrity and security of your data.
SSH-Agent and OpenSSH are tools in Windows that can be used to authenticate to remote Git repositories, such as GitLab, GitHub, Azure DevOps, etc. Once set up as a service that stores your various SSH keys, this can facilitate authentication without entering a password each time, removing the irritation of entering a password every time you wish to push/pull/etc. from a Git repository.
Prerequisites
- The OpenSSH Client optional service must be enabled on your machine, and OpenSSH must be added to your PATH environment variable. You can read how to do that here.
- A remote Git repository that you wish to access. We will use a GitLab repository for this article; however, the process will be similar for other Git management providers.
- Git must be installed on your machine.
How to Install the SSH-Agent Service in Windows
Using an elevated PowerShell window (run as admin), execute the following command to install the SSH-Agent service and configure it to start automatically when you log into your machine:
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service
To avoid needing to restart your system to get the service running for the first time, execute this command:
start-ssh-agent.cmd
Setting up an SSH Key Pair to Access a Git Remote Provider
Using a command line tool such as Bash or PowerShell, you should be able to follow these steps to create a local SSH key pair. For our example, we will create an ED25519 key, but you can create other keys such as an RSA.
Create a new SSH ED25519 key, giving it a useful comment:
ssh-keygen -t ed25519 -C "Git-Demo"
By default, the file will be stored in your local user’s SSH repository in Windows. You can choose another storage location if you wish or rename the file by entering a new file path to save the key. Leave it blank to stick with the default.
In our example, we rename the file from the default id_ed25519 to id_ed25519_git_demo:
You can also add a password if you like or leave this blank:
You will then be shown the key’s randomart image to confirm creation:
Copy the contents of the public key to your clipboard. You can read this key with the following command:
cat path\to\ssh\key.pub
For example, our code is likely:
cat C:\Users\chastie/.ssh\id_ed25519_git_demo.pub
Note: We access the public key with the .pub suffix.
A sample is shown here. You can then select this and copy it with a right-click of your mouse:
In GitLab (or the appropriate location of your Git remote repository), you can now add this public key to your user profile. In GitLab, you can do this by adding it under the SSH Keys section of your user settings:
Test that you can connect to the repository when using the SSH private key directly with this command:
ssh -i path/to/ssh/private/key -T git@host
For example, our command could be:
ssh -i C:\Users\chastie/.ssh\id_ed25519_git_demo -T git@gitlab.mycompany.com or ssh -i C:\Users\chastie/.ssh\id_ed25519_git_demo -T git@github.com
We have now established an SSH key pair that can authenticate to our Git remote provider. It remains to set this up in the SSH-Agent service to automatically provide access. We can demonstrate the issue by attempting the same connection, but without specifically naming the SSH key, with the command below:
ssh -T git@host
As we can see, if we execute this command without specifying an SSH key, we are prompted for a password:
Adding the SSH Key to the SSH-Agent Service
Our goal is to be able to connect to a Git repository without entering a password. At this stage, we have a working SSH key pair and the SSH-Agent service installed and running.
Execute the following command to add your SSH key to your SSH-Agent service:
ssh-add path/to/ssh/private/key
For our example, our command could be:
ssh-add C:\Users\chastie/.ssh\id_ed25519_git_demo
We can now test our connection to our Git remote provider without specifying a key and connect successfully:
ssh -T git@host
Configuring Git to Leverage the Windows SSH-Agent
In an elevated console (run as admin), execute the following command to modify your existing Git configuration to leverage the windows OpenSSH service as the core SSH command:
git config --global core.sshCommand C:/Windows/System32/OpenSSH/ssh.exe
Congratulations! You have now set up your environment to automatically authenticate to your Git remote provider through an SSH key pair, without using passwords. If you wish to facilitate access to any other Git remote providers, simply follow the same steps to generate a key pair ( as outlined above) and add it to your existing SSH-Agent service.
In this article, we will show how to configure SSH authentication in Windows using RSA or EdDSA keys. Let’s see how to generate public and private key pair on Windows and configure an OpenSSH server on Windows 10/11 or Windows Server 2019/2022 for key-based authentication (without passwords).
SSH key-based authentication is widely used in the Linux world, but in Windows, it has appeared quite recently. The idea is that the client’s public key is added to the SSH server, and when a client tries to connect to it, the server checks if the client has the corresponding private key. This way a remote user can authenticate in Windows without entering a password.
Contents:
- Generating an SSH Key Pair on Windows
- OpenSSH: Configuring Key-Based Authentication with Public Key on Windows
- Logging Windows with SSH Key Under Administrative User
Generating an SSH Key Pair on Windows
You must generate two SSH keys (public and private) on the client computer that you will use to connect to the remote Windows host running OpenSSH. A private key is stored on the client-side (keep the key safe and don’t share it with anyone!), and a public key is added to the authorized_keys file on the SSH server. To generate RSA keys on a Windows client, you must install the OpenSSH client.
On Windows 10/11 and Windows Server 2019/2022, the OpenSSH client is installed as an optional Windows feature using PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Open a standard (non-elevated) PowerShell session and generate a pair of ED25519 keys using the command:
ssh-keygen -t ed25519
By default, the ssh-keygen tool generates RSA 2048 keys. Currently, it is recommended to use ED25519 instead of RSA keys.
You will be prompted to provide a password to protect the private key. If you specify the password, you will have to enter it each time you use this key for SSH authentication. I did not enter a passphrase (not recommended).
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:xxxxxxxx myuser@computername The key's randomart image is: +--[ED25519 256]--+ +----[SHA256]-----+
Ssh-keygen will create the .ssh directory in the profile of a current Windows user (%USERPROFILE%\.ssh) and generate 2 files:
id_ed25519– private key (if you generated an RSA key, the file will be namedid_rsa)id_ed25519.pub– public key (a similar RSA key is calledid_rsa.pub
After the SSH keys are generated, you can add your private key to the SSH Agent service, which allows you to conveniently manage private keys and use them for authentication.
The SSH Agent service can store your private keys and provide them in the security context of the current user. Run the ssh-agent service and configure it to start automatically using PowerShell:
set-service ssh-agent StartupType ‘Automatic’
Start-Service ssh-agent
Add your private key to the ssh-agent database:
ssh-add "C:\Users\youruser\.ssh\id_ed25519"
Identity added: C:\Users\youruser\.ssh\id_ed25519 (youruser@computername)
Or as follows:
ssh-add.exe $ENV:UserProfile\.ssh\id_rsa
OpenSSH: Configuring Key-Based Authentication with Public Key on Windows
Now you need to copy your SSH public key to the SSH server. The SSH server in this example is a remote Windows 11 machine that has the OpenSSH service installed and configured.
Copy the id_ed25519.pub file to the .ssh directory in the profile of the user you will use to connect to the SSH server. For example, I have a user1 account on my remote Windows 11 device, so I need to copy the key to C:\Users\user1\.ssh\authorized_keys.
You can copy the public key to the SSH server from the client using SCP:
scp C:\Users\youruser\.ssh\id_rsa.pub [email protected]:c:\users\admin\.ssh\authorized_keys
You can add multiple public keys to a single authorized_keys file.
Public key authentication is disabled by default in the OpenSSH server on Windows. You can check this in the sshd_config. You can get a list of allowed authentication methods in OpenSSH by grepping the config file:
cat "C:\ProgramData\ssh\sshd_config"| Select-String "Authentication"
#PubkeyAuthentication yes #HostbasedAuthentication no #HostbasedAuthentication PasswordAuthentication yes #GSSAPIAuthentication no
In this example, the PubkeyAuthentication line is commented out, which means that this authentication method is disabled. Open the sshd_config file with Notepad and uncomment the line:
Notepad C:\ProgramData\ssh\sshd_config
PubkeyAuthentication yes
Also, you will have to disable the StrictModes option in the sshd_config configuration file. By default, this mode is enabled and prevents SSH key-based authentication if private and public keys are not properly protected. Uncomment the line #StrictModes yes and change it to StrictModes no
Now you can connect to your Windows SSH server without a password. If you have not set a password (passphrase) for the private key, you will automatically connect to your remote Windows host.
To connect to a remote host using a native SSH client, use the following command:
ssh (username)@(SSH server name or IP address)
For example:
ssh [email protected]
It means that you want to connect to a remote SSH server with the IP address 192.168.1.15 under the user1 account. SSH Agent service will automatically try to use your private key to authenticate on a remote host.
- If you do not want to use the ssh-agent service to manage SSH keys, you can specify the path to the private key file to be used for the SSH authentication:
ssh [email protected] -i "C:\Users\youuser\.ssh\id_ed25519" - To connect SSH host using a user account from an Active Directory domain, use the following format:
ssh [email protected]@192.168.1.15 -i <private_key_absolute_path>
When connecting for the first time, you need to add the fingerprint of the SSH server key to the trusted list. Type yes -> Enter.
The authenticity of host '192.168.1.15 (192.168.1.15)' can't be established. ECDSA key fingerprint is SHA256:xxxxxxx. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
ETW logging is used in Windows OpenSSH to store SSH logs instead of plain text files. You can check the SSH key-based authentication logs in the Windows Event Viewer (Application and Services Logs -> OpenSSH -> Operational).
If the SSH connection with the private key is successful, the following event will appear in the OpenSSH log:
EventID 4 sshd: Accepted publickey for locadm from 192.168.15.20 port 55772 ssh2: ED25519 SHA256:xxxxxxx
If you were not able to connect to your SSH server using your private key and you are still prompted to enter a password, the user account you are trying to connect to is likely a member of the local Windows administrators group (the group SID is S-1-5-32-544). We will discuss it later.
Logging Windows with SSH Key Under Administrative User
OpenSSH uses special key-based authentication settings for admin user accounts on Windows.
You need to use the C:\ProgramData\ssh\administrators_authorized_keys file instead of the authorized_keys key in the user profile. Add your public SSH key to this text file (for security reasons, only the Administrators and SYSTEM groups should have permission to read this file).
You can change the NTFS permissions on a file with:
- The icacls tool:
icacls.exe "C:\ProgramData\ssh\administrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F" - or using the Get-Acl and Set-Acl PowerShell cmdlets:
Get-Acl "$env:programdata\ssh\ssh_host_rsa_key" | Set-Acl "$env:programdata\ssh\administrators_authorized_keys"
After that, SSH key authentication works even if the StrictModes is disabled.
To use the authorized_keys file from a user profile and not to move the public key info to the administrators_authorized_keys file, you can comment out a line in the OpenSSH configuration file (C:\ProgramData\ssh\sshd_config).
#Match Group administrators # AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
Additionally, you can disable SSH password login in the sshd_config:
PasswordAuthentication no
Don’t forget to restart the sshd service after making the changes in the sshd_config.
restart-service sshd
If you set PasswordAuthentication no, and configure SSH key authentication incorrectly, then an error will appear when connecting via SSH:
[email protected]: Permission denied (publickey,keyboard-interactive).
You can use the PermitRootLogin option in OpenSSH on Linux to restrict SSH root login. This directive is not applicable in Windows OpenSSH, and you must use the DenyGroups parameter to deny SSH login under admin accounts:
DenyGroups Administrators
So, you have configured SSH authentication in Windows using a key pair. Now you can use this authentication method to securely access remote servers, automatically forward ports in the SSH tunnel, run scripts, and perform other automation tasks.
In this article I’m going to show you can use SSH on Windows machines. We’ll go over the installation of OpenSS, basic SSH configuration, as well as connecting to and from a Windows and Linux machine.
The Secure Shell (SSH) Protocol is a network protocol that allows secure access to interact with remote network resources over port 22. SSH is commonly used for remote login and command-line execution for administrative purposes. Microsoft Windows uses an implementation of OpenSSH to implement the SSH protocol and actively maintains this software project on GitHub under the openssh-portable repository.
Did you know that you can even use SSH to mount a filesystem with SSHFS, create a transparent proxy with SSHuttle, and copy files back and forth between systems using SCP? There are many amazing uses that includes the SSH protocol! If you’re curious about more implementations of the SSH protocol you can learn more here.
Installation
In order to use OpenSSH we need to first install the Microsoft.OpenSSH.Beta package using Microsoft Package Manager (winget). For those unfamiliar with the Windows Package Manager, I wrote a blog post on winget.
Searching For the OpenSSH Package
In order to find the OpenSSH package to install we are going to use the Windows Package Manager through a PowerShell terminal to search for available packages.
winget search openssh
Once we have the name of the package, Microsoft.OpenSSH.Beta we can verify this package by showing package details using winget.
Is OpenSSH Already Installed?
We can check if OpenSSH is installed or not using the winget list command.
winget list Microsoft.OpenSSH.Beta
winget list Microsoft.OpenSSH.Beta
If OpenSSH is already installed we can skip the installation process.
OpenSSH Package Metadata
When searching for applications and packages using Microsoft winget it’s a good idea to show the package metadata before installing, especially if this package is not something you’re familiar with.
winget show Microsoft.OpenSSH.Beta
winget show Microsoft.OpenSSH.Beta
Using the show command allows us to see critical information regarding this package including: publisher, source, release notes, and security fixes. Keeping up with package security is essential!
Installing the OpenSSH Package
Once we’ve found and verified the OpenSSH package we can move on to installing the package using winget. During the installation we can verify the Installer Url is indeed the URL we saw from the previous show command. The Windows Package Manager will also verify the hash for us!
winget install Microsoft.OpenSSH.Beta
Enabling the ssh-agent Service
Once installed we can ensure that the ssh-agent service is enabled and started on our Windows machine using a powershell terminal. It’s important to note that this must be done through an Administrator terminal.
Elevate Terminal
I suggest using gsudo to elevate the current terminal. The tool gsudo is the Windows equivalent of the Linux sudo command. If you don’t have gsudo already installed you can use this guide to setup gsudo.
If gsudo is already installed we can elevate the current terminal window with the following command.
Enable ssh-agent Service
Once the current terminal is elevated with Administrator privileges we can run use the Set-Service command to enable the ssh-agent service to be a persistent service which starts up automatically.
Set-Service ssh-agent -StartupType Automatic
Start ssh-agent Service
Once we have our ssh-agent enabled as a persistent service we can start this service directly with the Start-Service command.
Sequence of commands to enable & start ssh-agent service
Generate SSH Keys
After we have enabled and started the ssh-agent service we can move onto generating an ssh keypair. This can be accomplished using the ssh-keygen command. In our terminal run the following command.
This command will generate a new ssh key-pair for us and will ask us to provide the file to save the key as. Additionally, we will be asked to provide a key password, we can hit enter twice to use a passwordless key.
Generating a new ssh key-pair using the ssh-keygen command
Adding the SSH Key to the Authentication Agent
Once our ssh key-pair has been generated we can move onto adding our private key to the ssh agent using the ssh-add command. This important step adds our key to the authentication agent which we need in order to authenticate with our key-pair.
ssh-add 'C:\Users\admin\.ssh\win_id_rsa'
Connecting to Windows From Linux
After we’ve successfully added our ssh key to the authentication agent with ssh-add we are ready to test ssh authentication using our .pub public key.
In this example I’m going to connect to my Windows machine from my Linux machine. First we need to ensure that the public key we just generated is on the machine we want connect from. Since I’m using virtual machines I’ll simply move my key over using a shared folder from my host.
The Windows public ssh key located on my Linux machine
We also need to know the IP address of our Windows machine, we can find this information out easily with PowerShell with the Get-NetIPAddress command.
Get-NetIPAddress -AddressFamily IPv4 | Format-Table
Get-NetIPAddress command output
Once we have our public key on our Linux machine and the IP address of our Windows machine we are ready ssh to our Windows machine.
To confirm we are on a Linux machine we can use the uname -a command.
Running the uname -a command
To ssh to our Windows machine we can run the following command providing our username, IP address, as well as public key.
ssh admin@172.16.186.151 -i win_id_rsa.pub
Running the SSH command to connect to Windows from Linux
If successful you’ll see a Microsoft Windows command-line terminal from your Linux.
Connecting to Linux From Windows
If we would like to connect to our Linux machine from our Windows machine we can perform the opposite steps. Similar to the above we need to do the following (if you already have a key-pair for your Linux machine setup feel free to skip the “Ensuring SSH Is Installed on Linux” section).
Ensuring SSH Is Installed on Linux
In this section I will use an Ubuntu Desktop as my Linux machine. We need to perform some administrative tasks to ensure that we are able to connect to our Linux machine from Windows
Install SSH
If SSH is not already installed we can install using apt install.
Running the sudo apt install -y ssh
Start & Enable the SSH Service
Once the ssh package as well as dependant packages are installed we can start the ssh service using the following the systemctl command.
You can also ensure that the ssh starts in a persistent manner when the Ubuntu machine boots.
sudo systemctl enable ssh
Generate SSH keys
Similar to how we generated a key-pair on Windows, we can use the same command on Linux to generate a new SSH key-pair. We can do so with the ssh-keygen command.
Like when we did with Windows we’ll be required to give the output location of our key-pair as well as provide an optional password.
Running the ssh-keygen command
Adding the SSH Key with ssh-add
Once we’ve generated the ssh key we can proceed to add the private key to the ssh authentication agent using ssh-add command by running.
ssh-add /home/gothburz/.ssh/ubuntu_id_rsa
Running the ssh-add command
Copy SSH Public Key to Windows Machine
Once we have ensured that ssh is properly up and running including adding our key-pair to the ssh authentication agent we need to ensure we copied our public key over to our Windows machine
Since I’m using virtual machines I’ll simply move my key over using a shared folder from my host.
Verifying the Linux SSH public key with the ls command
Connecting to Linux from Windows Machine
Once we have ensured that our Linux machine is properly configured with SSH and that our public ssh key is on our Windows machine we can go ahead and initiate an SSH connection.
We can use the ssh command to initiate the connection from Windows to Linux using powershell.
Be sure to change your username@host as well as the path to the public key.
ssh gothburz@172.16.186.163 -i .\ubuntu_id_rsa.pub
Connecting to our Linux machine from Windows with the ssh command
Depending on your configuration you might be asked for a password as well. Once you’ve ran the ssh command and entered the correct password you should enter a new Linux terminal from Windows. Congrats!
Learn More About SSH
If you’d like to add a definitive guide to SSH to your library then I highly recommend the following book. Written for a wide audience, this book covers the Secure Shell (SSH) in great detail by providing a comprehensive guide for a plethora of use cases, features, and even contains in-depth case studies on large, sensitive computer networks.
Conclusion
In this blog post we looked at how to use the SSH protocol on Microsoft Windows using OpenSSH. We went through the following:
-
The OpenSSH installation process with the Windows Package Manager (WinGet)
-
The SSH configuration process
-
How to connect to Windows from Linux
-
How to connect to Linux from Windows
I hope you found this post insightful and useful in your day-to-day operations.
Let me know if you have any questions regarding SSH and happy connecting! 
