Сервер ssh windows server 2019

В современных версиях 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_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

2023 Update.

You’re better off looking at the following official documentation: https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse

While I’ve never had a problem with PowerShell remoting for remote command line interaction with Windows Server, I’ve often found that it isn’t something that many systems administrators, especially those that work in heterogeneous environments, are entirely at ease with. I’ve lost count of the number of times that I’ve seen experienced admins RDP across to a box running Windows Server so that they can interact with the operating system through a command prompt.

Windows Server 2019 and the most recent version of Windows 10 include the ability to install both an SSH client and an SSH server. Because most of us work with heterogenous systems, we are familiar with SSH’ing into a server or device to perform admin tasks. Now that it’s available and easy to configure on Windows Server 2019, I find myself using SSH, rather than other remote connection methods, as my default method of remotely connecting to servers, be they proximate or running in Azure.

To get an SSH client onto Windows 10 or Windows Server 2019, without using 3rd party software or installing Windows Subsystem for Linux, use the PowerShell command:

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

To add an SSH client and SSH server to Windows Server 2019, use the following PowerShell commands:

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

I have found it useful to add both client and server capability to Windows Server. This is also useful if the server will function a jump box. Once you’ve added the capability, you need to do a few things to get the SSH server working before you’re ready to go.

If you’re intending to use key based, rather than password based, authentication, you should also run the following command on the server to install an OpenSSH related PowerShell module that includes tools to help you configure that functionality:

Install-Module -Force OpenSSHUtils -Scope AllUsers

I also recommend running the following PowerShell commands on the server to install the Nano text editor, which allows you to edit text files through an SSH session. If you’re going to use key based authentication rather than passwords, you’ll need to edit one of the config files (I’ll explain what you need to do a little later in the article):

Set-ExecutionPolicy Bypass
Iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
choco install nano -y

The next thing you’ll need to do on your server is to configure the disabled ssh-agent service to automatically start and also configure the sshd service to automatically start. To do this, run the following PowerShell commands:

Set-Service -Name ssh-agent -StartupType ‘Automatic’
Set-Service -Name sshd -StartupType ‘Automatic’

The final step in getting SSH running on Windows Server 2019 is to run the following commands to start the relevant services:

Start-Service ssh-agent
Start-Service sshd

If you do all of this, you’ll be able to connect using password passed authentication from an SSH client using the syntax:

ssh username@hostname_or_IP_address

If you’re connecting to a domain account the format is

ssh username@domain@hostname_or_IP_address

The reality of SSH is that the vast majority of people that use it, use key based authentication rather than password based authentication. To get key based authentication working with Windows Server 2019’s SSH server, you’ll need to the following:

On the client change to the .ssh directory and run the command ssh-keygen accepting the defaults (you can change the name of the keys and provide a key password if you really want to, but that’s beyond the scope of this article)

Cd ~\.ssh\
Ssh-keygen

Doing this with the default values will create a public and private key. The private key will be id_rsa and the public key will be id_rsa.pub.

The next thing you should do is add your private key to your Windows security context. You can do this by running the following three commands:

Set-Service ssh-agent -StartupType ‘Automatic’
Start-service ssh-agent
Ssh-add ~\.ssh\id_rsa

Once you’ve done this, you’ll want to deploy your public key to the Windows Server 2019 server that you want to use SSH key based authentication with. To do this, perform the following steps (where chancellor is the name of the user account you’re configuring SSH key based authentication for):

Ssh chancellor@172.16.0.15 mkdir c:\users\chancellor\.ssh\
Scp c:\users\chancellor\.ssh\id_rsa.pub chancellor@172.16.0.15:C:\Users\Administrator\.ssh\authorized_keys

You’ll then need to run the following PowerShell command, located in that OpenSSHUtils PowerShell module I mentioned earlier, to configure some of the permissions for the authorized keys file. You might even want to SSH across to the server using password based authentication to do this:

Repair-AuthorizedKeyPermission C:\users\Chancellor\.ssh\authorized_keys

Because the PowerShell cmdlet doesn’t entirely work as it should, you’ll also need to run the following command as “NT SERVICE\sshd” should not have any permissions to the authorized_keys file (if it does, key based authentication doesn’t seem to work)

Icacls authorized_keys /remove “NT SERVICE\sshd”

The final step you’ll need to take requires you to edit the c:\ProgramData\ssh\sshd_config file, which you can do using the nano text editor and comment out the following lines (which are at the end of the file):

# Match Group administrators                                                   
#       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys 

You may need to do this locally on the Windows Server 2019 box. Once this is done, you can restart the sshd service (restart-service sshd) and you will be able to connect from your client using key based authentication.

If you want to learn about advanced configuration options for OpenSSH server on Windows Server 2019, consult the following article: https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_server_configuration?WT.mc_id=ITOPSTALK-blog-orthomas

Мы ранее уже устанавливали OpenSSH сервер на Windows Server 2012 R2. Тогда мы скачивали пакет с GitHub.

Установка OpenSSH Server в Windows Server 2012 R2

Инструкция не потеряла свою актуальность, но в Windows Server 2019 теперь можно установить OpenSSH Server гораздо проще через Feature on Demand (FoD). Пакет OpenSSH Server включен в Feature on Demand (FoD) современных версий Windows 10 (начиная с 1803), Windows 11 и Windows Server 2022/2019. При этом все основные настройки выполняются автоматически, даже правило в Firewall создаётся и применяется.

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

Установим OpenSSH сервер через FoD. Открываем настройки, Apps & features.

ssh

Нажимаем Manage optional features.

ssh

+ Add a feature.

ssh

Находим OpenSSH Server → Install.

ssh

Ничего сложного. Если установка не получается, то можно обратить внимание на этот разбор:

Windows — ошибка при установке дополнительных компонентов

Есть альтернативные способы установки, например, через 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

Можно проверить что пакет установлен через PowerShell:

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

ssh

State : Installed.

Запустим службу, можно вручную через GUI:

ssh

А можно через PowerShell:

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

ssh

Служба запускается на 22 порту:

netstat -tan | find ":22 "

ssh

Как я уже говорил, входящее правило на Firewall для 22 порта при таком способе установки создаётся автоматически.

Настройка доступа

Конфигурационный файл находится здесь: C:\ProgramData\ssh\sshd_config.

ssh

Собственно, OpenSSH конфигурируется здесь. Информацию о конфигурации можно почерпнуть здесь:

https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_server_configuration

Например, чтобы разрешить доступ по OpenSSH определённой группе пользователей, допишу в конец файла:

DenyUsers *
AllowGroups my_domain\my_group_for_ssh_access

Другой вариант, разрешить доступ определённым пользователям и сразу выполнить для них установку корневой директории через ChrootDirectory.

AllowUsers my_domain\user1 my_domain\user2

Match User my_domain\user1
       ChrootDirectory D:\folder_1

Match User my_domain\user2
       ChrootDirectory D:\folder_2

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

Приобрести оригинальные ключи активации Windows Server можно у нас в каталоге от 1190 ₽
Установка OpenSSH сервера в Windows

OpenSSH сервер включен в современные версии Windows 10 (начиная с 1803), Windows 11 и Windows Server 2022/2019 как Feature on Demand (FoD). Установить его можно несколькими способами.

1. Установка через PowerShell:

Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*' | Add-WindowsCapability -Online

2. Установка через DISM:

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

3. Через панель «Параметры»:

— Перейдите в Настройки -> Приложения -> Дополнительные компоненты -> Добавить компонент.

— Найдите OpenSSH Server и нажмите Установить.

4. Установка с помощью MSI пакета:

Вы можете установить OpenSSH с помощью MSI установщика, доступного на GitHub:

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

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

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

State : Installed

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

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

ssh-agent (для управления ключами если вы настроили SSH аутентификацию по ключам)

sshd (собственно сам SSH сервер)

1. Настройка автозапуска SSH службы:

Выполните команду PowerShell для включения автозапуска SSH сервера:

Set-Service -Name sshd -StartupType 'Automatic'

Start-Service sshd

2. Проверка порта SSH:

Убедитесь, что сервер слушает на порту TCP:22:

netstat -na | find ":22"

3. Настройка брандмауэра:

Убедитесь, что брандмауэр разрешает подключения по SSH:

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

Если правило отключено, включите его:

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

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

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

Конфигурация файла sshd_config

Конфигурационный файл OpenSSH сервера находится по пути C:\ProgramData\ssh\sshd_config. Вы можете отредактировать его через любой текстовый редактор. Например, откройте файл с помощью блокнота:

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

1. Запрет подключения для пользователей/групп:

— Запретить подключение для определенного пользователя:

DenyUsers softcomputers\admin@192.168.1.10
DenyUsers corp\*

— Разрешить доступ только для локальной группы:

AllowGroups sshadmins

2. Изменение порта SSH:

Для смены порта измените значение директивы Port.

После изменений не забудьте перезапустить службу:

Restart-Service sshd

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

AllowGroups softcomputers\sshadmins

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

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

DenyGroups Administrators

Следующие директивы разрешают SSH доступ по ключам и по паролю

PubkeyAuthentication yes
PasswordAuthentication yes

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

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

restart-service sshd

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

Для подключения к Windows через SSH можно использовать любые SSH клиенты (например, PuTTY или встроенный клиент Windows). Пример команды для подключения:

ssh alexbel@192.168.31.102

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

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

alex@server1 – локальный пользователь Windows

alex@softcomputers.org@server1 – пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365)

softcomputers\alex@server1 – NetBIOS формат имени

Если используется аутентификация по Kerberos в домене, включите ее в конфигурационном файле:

GSSAPIAuthentication yes

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

ssh -K server1

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

Нажимаем — «Да»

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

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

admin@win10tst C:\Users\admin>

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

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

powershell.exe

Чтобы изменить командную оболочку (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

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

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

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

Логи SSH подключений пишутся в журнал событий Windows через Event Tracing for Windows (ETW). Чтобы просмотреть логи:

1. Откройте Event Viewer (eventvwr.msc).

2. Перейдите в Application and Services Logs -> OpenSSH -> Operational.

Пример события успешного подключения по паролю:

EventID: 4

sshd: Accepted password for user1 from 192.168.31.102 port 55432 ssh2

Если необходимо, вы можете настроить запись логов в текстовый файл. Для этого добавьте в файл sshd_config директивы:

SyslogFacility LOCAL0

LogLevel INFO

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

Теперь вы знаете, как настроить и использовать OpenSSH сервер на Windows для удаленного подключения по защищенному протоколу SSH.

❗ This post is over six years old. It may no longer be up to date. Opinions may have changed.

On hackernews I saw a Microsoft blog post stating that Windows Server
2019 now includes OpenSSH. In this post I’ll try out both the client and server
on a Windows 2019 server, including how to login as a Active Directory Domain
user. All documentation from Microsoft on OpenSSH can be found here. The
bonus this time is how to elevate permissions via SSH on Windows, sudo but way
more complicated. This guide is also applicable on Windows 10, build 1809 and
up.

Installing OpenSSH on Windows

Fire up a powershell prompt as administrator and execute the following command
to see if it’s installed already:

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

Example output:

Name  : OpenSSH.Client~~~~0.0.1.0
State : NotPresent
Name  : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

If they are NotPresent, install them with the below powershell commands:

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

Example output for both:

Path          :
Online        : True
RestartNeeded : False

I had to install all Windows updates before the server part would install (up to
december 2018).

Start the openssh server and make sure it starts up automatically. Not required
when you only want to use the openssh client.

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

The setup automatically creates a firewall rule to allow OpenSSH. Check to make
sure it is actually created.

Get-NetFirewallRule -Name *ssh*

CMD or Powershell?

The default prompt when SSHing in to a windows server is cmd.exe. Rather bare
and sparse, I recommend you change that to Powershell. It’s Windows, so it has
to be changed in the registry, but there is a powershell command to do so:

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

If you have installed bash you can set that to be the default shell by
changing the full -Value path to the bash.exe binary.

Windows OpenSSH client

Using SSH on Windows (open up a powershell window) is as simple as typing in the
command and the server to connect to:

ssh user@example.org

You will be prompted for a password, type it, and you’re in.

However, using passwords is insecure and will get your server compromised
(eventually). SSH has the concept of keys, cryptographicly secure public private
keys which can be used for authentication. The rest of this section covers the
creation and placement of an SSH keypair on Windows.

You want to install the ssh-agent if you are going to use Windows as ssh
client:

Install-Module -Force OpenSSHUtils -Scope AllUsers
Start-Service ssh-agent
Set-Service -Name ssh-agent -StartupType 'Automatic'

With an ssh-agent, you don’t have to type the password for your private key
every time you SSH to a server.

Generating an SSH keypair on Windows

Generate your SSH keypair with the following command:

ssh-keygen

Example output:

Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\Remy/.ssh/id_rsa):
Created directory 'C:\Users\Remy/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Remy/.ssh/id_rsa.
Your public key has been saved in C:\Users\Remy/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:FSpFs/BY0U8k+kCp6IDW5K4+Lw4RO7kS8c6TrzIXNF8 remy@WIN-EXAMPLESRV
The key's randomart image is:
+---[RSA 2048]----+
|      ..B+o..    |
|   .   B.=.o.    |
|o.+  .o.* .o     |
|.B+o. E. +  .    |
|B.o= .  S .      |
| B.oo            |
|+ *.             |
|=+.o             |
|o*=o.            |
+----[SHA256]-----+

Make sure to enter a passphrase. Create a backup of the folder
(C:\Users\Username\.ssh), if you loose that private key you won’t be able to
login anymore.

Remember that private key files are the equivalent of a password should be
protected the same way you protect your password. To help with that, use ssh-
agent
to securely store the private keys within a Windows security context,
associated with your Windows login. To do that, start the ssh-agent service as
Administrator (we already did that when installing) and use ssh-add to store
the private key:

ssh-add ~\.ssh\id_rsa

Add the key to another Windows server

Using the following commands we can copy our public key (not the private, never
share your private parts) to a server running SSH. I assume you know how to do
this on Linux, this example is for another Windows server. The permissions are
managed differently.

In this example I use the user remy in the AD domain SPCS. The format then
to login is remy@spcs@example.org, the first part (remy@spcs) is the
username (and AD domain), the last part (@example.org) is the server to
connect to.

Create the folder where the authorized_keyfile belongs:

ssh remy@spcs@example.org mkdir C:\users\remy\.ssh\

Use scp to copy the public key file generated previously:

scp C:\Users\Remy\.ssh\id_ed25519.pub remy@spcs@example.org:C:\Users\remy\.ssh\authorized_keys
# note that my local user (leftmost part) is also remy. The server path is the rightmost part.

Change the permissions on the authorized_keys file on the server, otherwise
ssh will ignore the file:

ssh --% remy@spcs@example.org powershell -c $ConfirmPreference = 'None'; Repair-AuthorizedKeyPermission C:\Users\Remy\.ssh\authorized_keys

Example output:

  [*] C:\Users\Remy\.ssh\authorized_keys

'NT SERVICE\sshd' needs Read access to 'C:\Users\Remy\.ssh\authorized_keys'.
Shall I make the above change?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
'NT SERVICE\sshd' now has Read access to 'C:\Users\Remy\.ssh\authorized_keys'.
      Repaired permissions

The OpenSSHUtils powershell module needs to be installed for the Repair-
AuthorizedKeyPermission
cmdlet to work.

Install-Module -Force OpenSSHUtils -Scope AllUsers

You can now login to the Windows server using your private key.

Windows OpenSSH server

The Windows OpenSSH server is quite simple to configure. It has the regular
sshd_config file for settings, with some parts specific to Windows.

This is a screenshot where I SSH into a Windows server using my linux
workstation:

OpenSSH server configuration

This section is specifically for Windows related settings. I assume you know how
to configure openssh on linux.

The server reads it’s configuration from %programdata%\ssh\sshd_config. You
can copy and paste that path into a Windows Run dialog (WIN+R) to open
Explorer in the correct location.

When configuring user/group based rules with a domain user or group, use the
following format: user?domain*. Windows allows multiple of formats for
specifying domain principals, but many will conflict with standard Linux
patterns. For that reason, * is added to cover FQDNs. Also, this approach uses
? instead of @ avoids conflict with the username@host format.

To allow all users from the domain EXAMPLE in group Domain Admins to login
via SSH:

AllowGroups "EXAMPLE\Domain Admins"

It’s better to create a specific security group (e.g. sshusers) and add the
Domain Admins as a member. With a seperate group you can give or restrict the
ssh permissions more granulary.

To allow local users (non-domain) or local groups:

AllowUsers localuser@192.168.2.23
AllowGroups sshusers

PermitRootLogin on Windows

PermitRootLogin is not applicable in Windows. To deny administrators from
logging in via SSH, use a DenyGroups directive:

DenyGroups Administrators

For Windows OpenSSH, the only available authentication methods are password
and publickey.

At the bottom of this article there is an alternative to sudo. How otherwise
would you elevate permissions? Do note that it is quite complex.

AuthorizedKeysFile location on Windows

The default AuthorizedKeysFile locations are .ssh/authorized_keys and
.ssh/authorized_keys2. This is in the users home folder (C:\Users\Username)
(or the profile image path). If required, an absolute path can be provided
(D:\folder\authorized_keys).

Tips and tricks

Here are a few tips on Windows and SSH I found while using it for some time.

ssh-copy-id

From a linux machine, the command ssh-copy-id can be used to copy your public
key easily to another linux machine. This does not work on Windows:

$ ssh-copy-id administrator@10.0.0.133
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
administrator@10.0.0.133's password:
'exec' is not recognized as an internal or external command,
operable program or batch file.
'cat' is not recognized as an internal or external command,
operable program or batch file.
The system cannot find the path specified.

You need to use the above commands listed under the SSH client section to copy
the key and fix the permissions.

sudo

As you’ve denied access to Administrators via SSH (just as you would not allow
root login on Linux), you now need to have a way for people to elevate their
permissions. On linux you would use sudo su - or the likes. On Windows, there
is no sudo. There is also no way to elevate permissions of an already running
process.

Using the runas command fails because it cannot create a new window or ask UAC
(because you’re in a console SSH session).

There is a complex way of elevating your privileges. You need to run this in a
powershell session as your user. First you create a Credentials object which
has the username and password of the Administrator user. Then you use that
$Cred object with either Invoke-Command to run a single noninteractive
command, or with Enter-PSSession to get an interactive Powershell.

Note that you first need to ssh into your windows server and start powershell.
This can be done with one command:

ssh user@windows.example.org powershell

Non-interactive example:

$Username = 'Administrator'
$Password = 'P@ssw0rd'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

Invoke-Command -Credential $Cred -ComputerName localhost -scriptblock { cmd.exe /c whoami }

Example output:

win-doipgfhik47\administrator

Interactive shell example:

$Username = 'Administrator'
$Password = 'P@ssw0rd'
$Pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Pass

Enter-PSSession -ComputerName localhost -Credential $Cred

Example output:

[localhost]: PS C:\Users\Administrator\Documents> whoami
win-doipgfhik47\administrator

This is a screenshot of the entire process:

Note that this by default only works on localhost, not from a remote computer.
Unless you change the trustedhosts you will get an Access denied error.

This is also not really like sudo, but more like setting up a new ssh session
from localhost to localhost as root. (But, with powershell remoting).

Tags: microsoft
, openssh
, server
, ssh
, tutorials
, windows
, windows-server

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Брандмауэр windows код ошибки 0x8007042c
  • Synology assistant download windows 10
  • Как разогнать windows 10 домашняя
  • Почему процессор i7 7700hq не поддерживает windows 11
  • Docker run volumes windows