Ssh server for windows server

В современных версиях Windows уже есть встроенный SSH сервер на базе пакета OpenSSH. В этой статье мы покажем, как установить и настроить OpenSSH сервер в Windows 10/11 и Windows Server 2022/2019 и подключиться к нему удаленно по защищенному SSH протоколу (как к Linux).

Содержание:

  • Установка сервера OpenSSH в Windows
  • Настройка SSH сервера в Windows
  • Sshd_config: Конфигурационный файл сервера OpenSSH
  • Подключение по SSH к Windows компьютеру
  • Логи SSH подключений в Windows

Установка сервера OpenSSH в Windows

Пакет OpenSSH Server включен в современные версии Windows 10 (начиная с 1803), Windows 11 и Windows Server 2022/2019 в виде Feature on Demand (FoD). Для установки сервера OpenSSH достаточно выполнить PowerShell команду:

Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH.Server*’ | Add-WindowsCapability –Online

Или при помощи команды DISM:

dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0

Если ваш компьютер подключен к интернету, пакет OpenSSH.Server будет скачан и установлен в Windows.

Также вы можете установить сервер OpenSSH в Windows через современную панель Параметры (Settings -> Apps and features -> Optional features -> Add a feature, Приложения -> Управление дополнительными компонентами -> Добавить компонент. Найдите в списке OpenSSH Server и нажмите кнопку Install).

Установка openssh сервера из панели параметры windows 10

На изолированных от интернета компьютерах вы можете установить компонент с ISO образа Features On Demand (доступен в личном кабинете на сайте Microsoft: MSDN или my.visualstudio.com). Скачайте диск, извлеките его содержимое в папку c:\FOD (достаточно распаковать извлечь файл
OpenSSH-Server-Package~31bf3856ad364e35~amd64~~.cab
), выполните установку из локального репозитория:

Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online -Source c:\FOD

Также доступен MSI установщик OpenSSH для Windows в официальном репозитории Microsoft на GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases/). Например, для Windows 10 x64 нужно скачать и установить пакет OpenSSH-Win64-v8.9.1.0.msi. Следующая PowerShell команда скачает MSI файл и установит клиент и сервер OpenSSH:

Invoke-WebRequest https://github.com/PowerShell/Win32-OpenSSH/releases/download/v8.9.1.0p1-Beta/OpenSSH-Win64-v8.9.1.0.msi -OutFile $HOME\Downloads\OpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing

msiexec /i c:\users\root\downloads\OpenSSH-Win64-v8.9.1.0.msi

установочный msi файл openssh server для windows

Также вы можете вручную установить OpenSSH сервер в предыдущих версиях Windows (Windows 8.1, Windows Server 2016/2012R2). Пример установки Win32-OpenSSH есть в статье “Настройка SFTP сервера (SSH FTP) в Windows”.

Чтобы проверить, что OpenSSH сервер установлен, выполните:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Ser*'

State : Installed

проверить что установлен OpenSSH сервер в windows 10

Настройка SSH сервера в Windows

После установки сервера OpenSSH в Windows добавляются две службы:

  • ssh-agent (OpenSSH Authentication Agent) – можно использовать для управления закрытыми ключами если вы настроили SSH аутентификацию по ключам;
  • sshd (OpenSSH SSH Server) – собственно сам SSH сервер.

Вам нужно изменить тип запуска службы sshd на автоматический и запустить службу с помощью PowerShell:

Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd

Start-Service sshd - запустить openssh

С помощью nestat убедитесь, что теперь в системе запущен SSH сервер и ждет подключений на порту TCP:22 :

netstat -na| find ":22"

nestat - порт 22 ssh сервера windows

Проверьте, что включено правило брандмауэра (Windows Defender Firewall), разрешающее входящие подключения к Windows по порту TCP/22.

Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled

Name DisplayName Description Enabled
---- ----------- ----------- -------
OpenSSH-Server-In-TCP OpenSSH SSH Server (sshd) Inbound rule for OpenSSH SSH Server (sshd) True

правило firewall для доступа к windows через ssh

Если правило отключено (состоянии Enabled=False) или отсутствует, вы можете создать новое входящее правило командой New-NetFirewallRule:

New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

Рассмотрим, где храниться основные компоненты OpenSSH:

  • Исполняемые файлы OpenSSH Server находятся в каталоге
    C:\Windows\System32\OpenSSH\
    (sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe и т.д.)
  • Конфигурационный файл sshd_config (создается после первого запуска службы):
    C:\ProgramData\ssh
  • Файлы authorized_keys и ssh ключи можно хранить в профиле пользователей:
    %USERPROFILE%\.ssh\

Sshd_config: Конфигурационный файл сервера OpenSSH

Настройки сервере OpenSSH хранятся в конфигурационном файле %programdata%\ssh\sshd_config. Это обычный текстовый файл с набором директив. Для редактирования можно использовать любой текстовый редактор (я предпочитаю notepad++). Можно открыть с помощью обычного блокнота:

start-process notepad C:\Programdata\ssh\sshd_config

Например, чтобы запретить SSH подключение для определенного доменного пользователя (и всех пользователей указанного домена), добавьте в конце файле директивы:

DenyUsers winitpro\[email protected]
DenyUsers corp\*

Чтобы разрешить подключение только для определенной доменной группы:

AllowGroups winitpro\sshadmins

Либо можете разрешить доступ для локальной группы:

AllowGroups sshadmins

По умолчанию могут к openssh могут подключаться все пользователи Windows. Директивы обрабатываются в следующем порядке: DenyUsers, AllowUsers, DenyGroups,AllowGroups.

Можно запретить вход под учетными записями с правами администратора, в этом случае для выполнения привилегированных действий в SSH сессии нужно делать runas.

DenyGroups Administrators

Следующие директивы разрешают SSH доступ по ключам (SSH аутентификации в Windows с помощью ключей описана в отдельной статье) и по паролю:

PubkeyAuthentication yes
PasswordAuthentication yes

Вы можете изменить стандартный SSH порт TCP/22, на котором принимает подключения OpenSSH в конфигурационном файле sshd_config в директиве Port.

sshd - смена порта ssh 22

После любых изменений в конфигурационном файле sshd_config нужно перезапускать службу sshd:

restart-service sshd

Подключение по SSH к Windows компьютеру

Теперь вы можете попробовать подключиться к своей Windows 10 через SSH клиент (в этом примере я использую putty).

Вы можете использовать встроенный SSH клиентом Windows для подключения к удаленному хосту. Для этого нужно в командной строке выполнить команду:

ssh [email protected]

В этом примере
alexbel
– имя пользователя на удаленном Windows компьютере, и 192.168.31.102 – IP адрес или DNS имя компьютера.

Обратите внимание что можно использовать следующие форматы имен пользователей Windows при подключении через SSH:

  • alex@server1
    – локальный пользователь Windows
  • [email protected]@server1
    –пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365)
  • winitpro\alex@server1
    – NetBIOS формат имени

В домене Active Directory можно использовать Kerberos аутентификацию в SSH. Для этого в sshd_config нужно включить параметр:

GSSAPIAuthentication yes

После этого можно прозрачно подключать к SSH сервер с Windows компьютера в домене из сессии доменного подключается. В этом случае пароль пользователя не указывается и выполняется SSO аутентификация через Kerberos:

ssh -K server1

При первом подключении появится стандартный запрос на добавление узла в список известных SSH хостов.

putty сохранить ключ

Нажимаем Да, и в открывшееся окне авторизуемся под пользователем Windows.

ssh сессия в win 10 на базе openssh

При успешном подключении запускается командная оболочка cmd.exe со строкой-приглашением.

admin@win10tst C:\Users\admin>

В командной строке вы можете выполнять различные команды, запускать скрипты и программы.

подключение к windows 10 через ssh

Я предпочитаю работать в командной строке PowerShell. Чтобы запустить интерпретатор PowerShell, выполните:

powershell.exe

powershell.exe в ssh сессии windows

Чтобы изменить командную оболочку (Shell) по умолчанию в OpenSSH с cmd.exe на PowerShell, внесите изменение в реестр такой командой:

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String –Force

openssh - изменить shell по умолчанию на powershell

Осталось перезапустить SSH подключение и убедиться, что при подключении используется командный интерпретатор PowerShell (об этом свидетельствует приглашение
PS C:\Users\admin>
).

powershell cli в windows 10 через ssh

В SSH сессии запустилась командная строка PowerShell, в которой работают привычные функции: авто дополнение, раскраска модулем PSReadLine, история команд и т.д. Если текущий пользователь входит в группу локальных администраторов, то все команды в его сессии выполняются с повышенными правами даже при включенном UAC.

Логи SSH подключений в Windows

В Windows логи подключений к SSH серверу по-умолчанию пишутся не в текстовые файлы, а в отдельный журнал событий через Event Tracing for Windows (ETW). Откройте консоль Event Viewer (
eventvwr.msc
>) и перейдите в раздел Application and services logs -> OpenSSH -> Operational.

При успешном подключении с помощью к SSH серверу с помощью пароля в журнале появится событие:

EventID: 4
sshd: Accepted password for root from 192.168.31.53 port 65479 ssh2

события подключения к openssh сервер windows в event viewer

Если была выполнена аутентификация с помощью SSH ключа, событие будет выглядеть так:

sshd: Accepted publickey for locadm from 192.168.31.53 port 55772 ssh2: ED25519 SHA256:FEHDEC/J72Fb2zC2oJNb45678967kghH43h3bBl31ldPs

Если вы хотите, чтобы логи писались в локальный текстовый файл, нужно в файле sshd_config включить параметры:

SyslogFacility LOCAL0
LogLevel INFO

Перезапустите службу sshd и провеьте, что теперь логи SSH сервера пишутся в файл C:\ProgramData\ssh\logs\sshd.log

текстовый sshd.log в windows

Прежде всего, вы можете спросить, зачем нам вообще нужен SSH-сервер на Windows-сервере? В среде Windows SSH может показаться не очень полезным. В конце концов, у нас есть RDP и PowerShell Remoting с WinRM, которые уже обеспечивают мощные возможности удаленного управления. Тем не менее, SSH в Windows определенно имеет свои преимущества. Среди них можно выделить такие вещи, как:

  • Простое подключение и управление Windows-серверами из Linux или MacOS с помощью встроенных инструментов.
  • Подключение из систем Windows к серверам Linux — это простое решение с интегрированным SSH-клиентом. Есть много администраторов Linux, которые должны управлять серверами на работе с помощью ОС Windows, и всегда должны устанавливать некоторые дополнительные инструменты, такие как PuTTY или WinSCP. Теперь они могут использовать знакомые команды SSH прямо из командной строки Windows.
  • Используются те же инструменты удаленного управления для серверов Linux и Windows (SSH, SCP, аутентификация с открытым ключом и т. д.).
  • Кроссплатформенный PowerShell Remoting. PowerShell Core использует SSH для включения удаленного сеанса PowerShell в Windows, MacOS и Linux. В отличие от WinRM PowerShell Remoting — Windows PowerShell работает только на Windows.
  • Вместе с подсистемой Windows для Linux вы можете получить Linux-подобные сеансы SSH с Bash и обычные инструменты Linux также на сервере Windows, который позволяет администраторам Linux использовать свои знания для управления системами Windows.
  • И наоборот: администраторы Windows могут использовать PowerShell для управления сервером Linux, если на нем будет присутствовать соответствующий shell от Microsoft.
  • Просто другой вариант для удаленного управления, который дает еще большую гибкость.

Установка OpenSSH в Windows Server 2019

  • Используя GUI

Открываем SettingsApps & featuresManage optional features:

Раздел apps features=

Нажимаем Add a feature, ищем OpenSSH ServerInstall:

Установка OpenSSH Server

На предыдущем экране дожидаемся окончания процесса инсталляции. OpenSSH сервер можем считать установленным.

Обращаем внимание, что установка этим методом автоматически создаст правило Windows Firewall, с названием «OpenSSH-Server-In-TCP», открывающее 22 порт для входящих подключений.

Используя PowerShell:

Проверим, присутствует ли на нашей системе встроенный OpenSSH:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'

В ответ должны получить:

Name : OpenSSH.Client~~~~0.0.1.0
State : NotPresent #или Install, если клиент уже установлен
Name : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

Устанавливаем клиент, если он не установлен:

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

Для установки сервера вводим:

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

В обоих случаях вывод должен быть следующим:

Path :
Online : True
RestartNeeded : False

Первичная конфигурация SSH-сервера

По умолчанию при подключении к OpenSSH-серверу используется командная строка Windows. Вы можете использовать практически любую оболочку на вашем компьютере с Windows через SSH-соединение. Даже возможно использовать Bash, когда подсистема Windows для Linux (WSL) также установлена на целевой машине. Также возможно изменение оболочки по умолчанию на SSH-сервере на нечто иное, чем командная оболочка. Для этого ключ реестра «DefaultShell» необходимо изменить.

Сделать это можно как через редактор реестра regedit.exe, открыв в нем следующий путь: HKEY_LOCAL_MACHINESOFTWAREOpenSSH и изменив в нем параметр DefaultShell, указав в нем полный путь до исполняемого файла необходимой командной строки, например:

C:WindowsSystem32WindowsPowerShellv1.0powershell.exe

Тоже самое можно сделать используя PowerShell:

New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String -Force

Проверим настройки Windows Firewall, используя для этого PowerShell:

Get-NetFirewallRule -Name *ssh*

Введя данную команду мы получим параметры правила, разрешающего SSH-подключение к серверу. Если правила не оказалось, введем следующую команду, создав его:

New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

Запуск службы OpenSSH

После установки функции SSH-сервера нам остается только его запустить:

Start-Service sshd

Опционально можно установить для службы sshd автоматический запуск:

Set-Service -Name sshd -StartupType 'Automatic'

Подключение к серверу

Теперь мы готовы к работе и можем подключиться через установленное приложение к нашему хосту. Это можно осуществить либо с Windows 10, компьютера с Linux, с putty.exe на более старой машине с Windows, либо с Bash в настольной операционной системе от Microsoft. Все, что вам нужно, это найти какой-либо SSH-клиент, ввести в него имя пользователя, имя вашего сервера или IP-адрес и подключиться.

Для SSH-клиента в PowerShell синтаксис будет таким:

Ssh username@servername

При первом подключении с неизвестного хоста будет показано следующее сообщение:

Сообщение о том, что хост подключения будет добавлен в список известных хостов сервера

Ответив на него yes, хост подключения будет добавлен в список известных хостов сервера. После чего необходимо ввести пароль пользователя (по соображениям безопасности вводимые символы отображаться не будут). После успешного подключения отобразится интерфейс используемой командной строки:

Windows PowerShell

Копирование файлов

Также, как с сервером OpenSSH в любой системе * nix, вы можете использовать SCP для копирования файлов на сервер или с сервера.
Например, администратор Linux может быстро получить файл журнала с сервера Windows с помощью той же команды, что и для сервера Linux.

scp username@servername:C:/inetpub/logs/LogFiles/W3SVC1/u_ex191017.log u_ex191017.log

Когда вы подключаетесь из Bash/*nix к машине с Windows, нужно помнить, что пути Windows также должны указываться с обычными косыми чертами Unix вместо обратных косых черт. Например, C:/Windows вместо C:Windows.

sshd_config

Аналогично операционным системам семейства Linux, OpenSSH Server в Windows имеет в своем составе особый файл, где хранятся все параметры для выполнения более подробных настроек. Например,  для ограничения входа.

По умолчанию файл конфигурации находится в «%programdata%sshsshd_config».
Самые различные настройки, применимые к этому файлу можно найти на сайте https://man.openbsd.org/sshd_config.

Кроме того, у Microsoft есть документация для специфичных настроек Windows.

Больше информации

Дополнительную информацию об OpenSSH в Windows можно найти на сайте docs.microsoft.com или в проекте GitHub разветвления OpenSSH от Microsoft.

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

In this tutorial, I will show you how to install SSH server (OpenSSH) on Windows Server 2019/2022.

As of Windows Server 2019, the OpenSSH server is a native additional feature.

For previous versions of Windows Server a tutorial is available here: OpenSSH client and server – installation on Windows Server 2012R2 and 2016

Using an SSH server on Windows Server facilitates remote administration and can be used to “replace” WinRM. Its use also facilitates the use of software like Ansible, Jenkins …

Open settings

From the start menu, click on Settings.

Access Applications

In the list of WIndows settings, open Applications.

Open optional features

Click on optional features.

Open Add additional functionality

Click on Add a feature.

In the search box enter SSH to filter the features.

Select OpenSSH Server

Select the OpenSSH Server feature and click Install.

Wait during the installation

Wait while the OpenSSH server is installed on Windows Server, the installation requires the server to be connected to the Internet.

Once the installation is complete, close the settings

Once the OpenSSH server is installed, close Windows settings.

Open the services.msc console and find the OpenSSH Server service

Open the MMC services.msc console and look in the list for the OpenSSH Server service, we can see that it is not started and in Manual starting. Click on Start.

Change the startup mode

If necessary, open the properties of the service and change the start type to Automatic so that it is always started.

Connect to Windows server with SSH

If the firewall is enabled, ensure that port 22 allows incoming connections. From another computer from an SSH client, connect:

ssh ip_server

During the first connection, you must accept the certificate.

In the tutorial, I am using servers that are members of the same domain, so the connection is established with my account on the server where I use the client.

It is possible to use another user DOMAIN\login@ip_server

Execute commands

Once connected, use the ms-dos and PowerShell commands to manage the server.


You now know how to install and use an OpenSSH server on Windows Server.

I find this alternative to WinRM interesting in particular for connecting to Workgroup servers, because WinRM requires a particular configuration.

If you want to change the configuration of the SSH server, the sshd_config configuration file is located in the following location: C: \ ProgramData \ ssh

В этой статье мы рассмотрим, как установить SSH сервер (OpenSSH) на Windows Server и использовать его для удаленного управления сервером с помощью PowerShell по протоколу SSH.

Для удаленного управления компьютерами и серверами через PowerShell можно воспользоваться возможностями протокола WinRM, однако для более гладкого стыка с Linux системами удобнее использовать единый протокол удаленного управления — SSH. Одним из проектов команды Microsoft, занимающейся разработкой функционала PowerShell, является портирование популярного открытого сервера OpenSSH на Windows системы. Проект называется Win32-OpenSSH

    Содержание:

  • Установка пакета OpenSSH
  • SSH авторизация в Windows по паролю
  • SSH с аутентфикацией по ключу
  • Подключение с клиента через модуль Posh-SSH

Установка пакета OpenSSH

Сервер Win32-OpenSSH для Windows можно установить, скачав дистрибутив с GitHub (https://github.com/PowerShell/Win32-OpenSSH), либо (гораздо проще), установив его через менеджер пакетов Chocolatey.

Если Chocolatey еще не установлен, установить его можно следующими командами PowerShell:

Set-ExecutionPolicy Unrestricted
iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex

Установка OpenSSH сервера после этого выполняется командой:

choco install openssh -params '"/SSHServerFeature /KeyBasedAuthenticationFeature"' –y

Данная команда выполнит установку как SSH сервера, так и клиента. Если нужно установить только клиент, нужно убрать аргумент param.

Сценарий установки автоматически создаст правило файервола, разрешающее подключение на 22 порт, и запустит службы sshd и ssh-agent.

Примечание. Если правило по каким-то причинам не создалось, вы можете создать его командой:

New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH

sshd

Для перезагрузки переменных окружения, выполните команду:

refreshenv

SSH авторизация в Windows по паролю

Для удаленного подключения к данному SSH серверу под локальным пользователем user1, воспользуйтесь такой командой:

ssh user1@192.168.1.100

После запуска команды, для авторизации нужно указать пароль пользователя user1. Если SSH-сервер включен в домен, можно авторизоваться и под пользователем Active Directory. Имя пользователя в этом случае указывается в формате domain\domain_user_name или domain_user_name@domain.

ssh –l domain_user_name@domain remotehost

SSH с аутентфикацией по ключу

Для беспарольного входа можно использовать авторизацию на сервере SSH по ключу. Сначала нужно сгенерировать ключ на клиенте (в процессе нужно указать ключевую фразу)

Ssh-keygen.exe

Ssh-keygen.exe

В результате в каталоге пользователя c:\users\username\.ssh появится два файла id_rsa и id_rsa.pub.

Теперь нужно запустить службу ssh-agent

Start-Service ssh-agent

И добавить в настройки агента путь к нашему закрытому ключу:

ssh-add.exe C:\users\username\.ssh\id_rsa

Затем нужно разрешить аутентфикацию по этому ключу на стороне сервера. Для этого, скопируйте файл открытого ключа(id_rsa.pub) на SSH сервер в файл C:\users\username\.ssh\authorized_keys. Либо, при наличии администартивного доступа сразу на обоих системах, скопировать файл можно так:

cat c:\users\username\.ssh\id_rsa.pub | Add-Content '\\192.168.1.100\c$\users\username\.ssh\authorized_keys'

Теперь службе сервера SSH нужно дать право на чтение данных их каталога.ssh.

icacls C:\users\username\.ssh /grant "NT Service\sshd:R" /T

Теперь можно подключится SSH-клиентом к серверу, указав параметр –i и путь к закрытому ключу:

Ssh –I c:\users\username\.ssh\id_rsa –l user@domain 192.168.1.100
Ssh
По умолчанию открывается командная строка cmd, но можно запустить и PowerShell:

ssh-powershell

Подключение с клиента через модуль Posh-SSH

Для удаленного подключения к SSH серверу, модуль Posh-SSH используется следующим образом:

Подключаемся к серверу с сохранением сессии и указанием ключа:

New-SSHSession myclient -KeyFile "c:\data\MyKeyPair.pem"

Выполним команду ifconfig в сессии с ID 0.

Invoke-SSHCommandStream "ifconfig" -SessionId 0

Для завершения сеанса, выполните:

Invoke-SSHCommand -SessionId 0 -Command "logout"

Удалим сессию:

Remove-SSHSession 0

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:

  1. 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.

Checking if the OpenSSH zip file exists
Checking if the OpenSSH zip file exists

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.

  1. 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.

Installing OpenSSH
Installing OpenSSH

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.

Creating a Windows Firewall Rule to allow Port 22
Creating a Windows Firewall Rule to allow Port 22

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.

Connecting via SSH into Azure VM
Connecting via SSH using Password Authentication

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.

Getting the hostname of the SSH server
Getting the hostname of the SSH server

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.

Changing the default OpenSSH shell
Changing the default OpenSSH shell

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.

Creating the administrators_authorized_keys file
Creating the administrators_authorized_keys file

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.

Opening advanced security settings
Opening advanced security settings

8. Then, confirm if the permissions are as shown like in the image below.

Viewing advanced security permission
Viewing advanced security permission

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).

Generating a new SSH key pair on the local computer
Generating a new SSH key pair on the local computer

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.

Deploying the public key to the Windows SSH server
Deploying the public key to the Windows SSH server

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.

Connecting with SSH into Azure VM using Public Key Authentication
Connecting with SSH using Public Key Authentication

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.

Creating the Certificate Authority (CA) Key on a Windows SSH server
Creating the Certificate Authority (CA) Key on a Windows SSH server

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 the id_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.

Signing the User Key
Signing the User Key

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.

Finding the SSH user certificate
Finding the SSH user certificate

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.

Emptying the administrators_authorized_keys
Emptying the administrators_authorized_keys

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.

Connecting with SSH using Certificate Authentication
Connecting with SSH using Certificate 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!

  • Ssh windows linux without password
  • Ssh connection to windows server
  • Ssh tunnel windows to windows
  • Ssh connection timed out windows
  • Ssh connection to linux from windows