С помощью встроенного пакета OpenSSH для Windows вы можете легко настроить безопасную передачу файлов между клиентом и серверов Windows по защищенному протоколу передачи файлов SFTP (Secure FTP). В этой статье мы покажем, как установить и настроить установить SFTP сервер в Windows 10/11 или Windows Server 2022/2019/2016/2012R2 с помощью встроенных средств (Win32-OpenSSH).
Содержание:
- Установка OpenSSH в Windows
- Настройка SFTP сервера на базе OpenSSH в Windows
- Подключение к SFTP серверу с помощью PowerShell и WinSCP
- Настройка SFTP аутентификации по ключам
Протокол SFTP (Secure File Transfer Protocol , Secure FTP или SSH FTP) это расширение протокола SSH, являющимся стандартом мира UNIX/Linux систем. Хотя с точки зрения пользователей он похож на FTP, но на самом деле это абсолютно другой протокол, не имеющий с FTP ничего общего. Данные между клиентом и сервером передаются по порту 22 через SSH туннель.
Основные преимущества протокола SFTP:
- Передача файлов и команд происходит внутри защищенной SSH-сессии;
- Для передачи файлов и команд используется одно соединение;
- Поддерживаются символические ссылки, доступны функций прерывания, возобновления передачи, удаления файла и другие;
- Обычно на каналах, где FTP работает медленно или с перебоями, SFTP-соединение работает более надежно и быстро;
- Возможность аутентификации с помощью SSH ключей.
Не нужно путать протоколы SFTP и FTPS. FTPS – это по сути обычный FTP с SSL сертификатом, а SFTP – это передача FTP данных и команд внутри SSH сессии.
В современные версии Windows по-умолчанию встроен порт OpenSSH для win32 (Win32-OpenSSH). Вы можете использовать его для организации защищенного SFTP сервера вместо таких сторониих продуктов как Core FTP, FileZilla, CYGWIN, OpenSSH, FTP Shell, IPSwitch и пр.
Установка OpenSSH в Windows
Пакет OpenSSH уже включен в операционную систему в современных билдах Windows 10 (начиная с 1803), Windows 11, Windows Server 2022/2019 в виде Feature on Demand (как и RSAT).
В этих версиях Windows вы можете установить сервер OpenSSH с помощью PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server*
Или с помощью DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
Также можно установить OpenSSH из графического интерфейса Windows 10 (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).
Чтобы проверить, установлен ли пакет:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
Исполняемые файлы OpenSSH находятся в каталоге:
C:\windows\system32\OpenSSH\
Конфигурационный файл sshd_config находится в каталоге C:\ProgramData\ssh (каталог создается после первого запуска службы).
Лог — c:\windows\system32\OpenSSH\logs\sshd.log
Файл authorized_keys и ключи хранятся в каталоге %USERPROFILE%\.ssh\.
В предыдущих версиях Windows 10, в Windows 8.1 или в Windows Server 2016/2012 R2 вам придется скачать Win32-OpenSSH для Windows с GitHub и установить вручную (https://github.com/PowerShell/Win32-OpenSSH/releases). Нам нужна версия для 64 битной версии Windows: OpenSSH-Win64.zip (4,15 Мб).
- Распакуйте содержимое архива в целевой каталог, к примеру:
C:\OpenSSH-Win
- Запустите командную строку PowerShell с правами администратора и перейдите в каталог OpenSSH:
cd C:\OpenSSH-Win
- Добавьте путь к каталогу OpenSSH в переменную окружения Path;
- Установите сервер OpenSSH:
.\install-sshd.ps1
должно появиться зеленое сообщение “sshd and ssh-agent services successfully installed”).
Настройка SFTP сервера на базе OpenSSH в Windows
Теперь вам нужно настроить OpenSSH для режима SFTP.
Включите автозапуск для службы SSHD и запустите ее с помощью следующих PowerShell команд управления службами:
Set-Service -Name sshd -StartupType ‘Automatic’
Start-Service sshd
С помошью PowerShell отройте в брандмауэре Windows порт TCP 22 для входящего трафика на SSH сервер:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
Откройте в любом текстовом редакторе конфигурационный файл «C:\ProgramData\SSH\sshd_config», найдите и проверьте значение директивы Subsystem sftp. Здесь должен быть указан файл sftp-server.exe.
Рассмотрим полезные директивы в конфигурационном файле sshd_config:
# разрешить подключение к OpenSSH только для пользователей из этой группы
AllowGroups corp\admingroup
# включить аутентификацию по паролю (нельзя использовать ключи SSH)
AuthenticationMethods password ForceCommand internal-sftp
#каталог для SFTP пользователей (по умолчанию пользователь подключается в каталог со своим профилем в папке C:\users\username)
ChrootDirectory C:\SFTPRoot
#Для каждого пользователя можно индивидуальную chrootdirectory:
Match User user1 ChrootDirectory c:\SFTPRoot\user1 ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
Match User user2 ChrootDirectory c:\SFTPRoot\user2 ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
Подключение к SFTP серверу с помощью PowerShell и WinSCP
Теперь вы может подключиться к вашему SSH серверу на Windows по протоколу SFTP. Ниже мы покажем, как подключиться к SFTP серверу с помощью бесплатного клиента клиент WinSCP, консоли PowerShell и встроенной утилиты sftp.exe.
В окне настройки подключения выберите протокол передачи файлов SFTP, укажите имя сервера и данные учетной записи Windows (в формате
user@domain
для доменных пользователей), под которой осуществляется подключение (возможно также настроить авторизацию по ключам). При первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.
При первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.
Если все настроено правильно, клиент должен подключиться к SFTP серверу и отобразить список файлов в домашнем каталоге пользователя (по умолчанию каталог с профилем пользователя).
С помощью привычного интерфейса файлового менеджера можно безопасно копировать файлы между сервером и клиентом по защищённому протоколу SFTP.
Для подключения к SFTP серверу из PowerShell можно использовать модуль Posh-SSH. Вы можете скачать установить модуль из PowerShell Gallery или офлайн:
Install-Module -Name Posh-SSH
Для подключения к SFTP серверу с помощью пароля, нужно получить имя пользователя и пароль через Get-Credential:
$usrCreds= Get-Credential
Теперь можно подключиться к вашем SFTPS серверу:
$SFTPSession = New-SFTPSession -ComputerName 192.168.13.200 -Credential $usrCreds
Теперь вы можете вывести список файлов в удаленном каталоге на SFTP сервере. В этом примере я получу список файлов на рабочем столе пользователя (профиль пользователя в этом случае будет являться корнем)
Get-SFTPChildItem -SFTPSession $SFTPSession -Path "desktop" –Recurse
Чтобы скачать файл с удаленного SFTP сервера:
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path "desktop/OpenVPNScript.log" -Destination c:\temp
Чтобы закачать файл с вашего компьютера на удаленный SFTP хост:
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:\Temp\mytestfile.log -Destination “desktop”
Завершить SFTP сессию:
Remove-SFTPSession -SFTPSession $SFTPSession
В Windows вы можете использоваться встроенную утилиту sftp.exe (устанавливается вместе с клиентом OpenSSH) для подключения к SFTP серверу.
Подключиться к sftp серверу:
sftp [email protected]
Подключиться с помощью ssh ключа:
sftp -i .ssh/id_rsa [email protected]
Вывести список файлов в удаленном каталоге:
pwd
Скачать файл с SFTP в локальный каталог на ваш компьютер:
get file-test1.txt
Загрузить файл с вашего компьютера на SFTP сервер:
put file-test2.txt
Закрыть сессию:
exit
Настройка SFTP аутентификации по ключам
Вы можете настроить SFTP аутентификацию по ключам. В этом случае при подключении к SFTP серверу вам не нужно будет указывать пароль пользователя.
Подробно настройка SSH аутентификации по ключам описана в этой статье.
Для этого нужно:
- Создать на вашем компьютере (SFTP клиент) ключи для пользователя, под которым вы будете подключаться к серверу:
ssh-keygen -t ed25519
- Утилита сгенерирует два файла
id_ed25519
(закрытый ключ для клиента) и
id_ed25519.pub
(открытый ключ для сервера); - Теперь нужно добавить ваш SSH ключ на сервер. Скопируйте файл id_ed25519.pub(или id_rsa.pub в зависимости от типа ключа) в каталог .ssh профиля пользователя, под которым вы будете подключаться к SFTP серверу. Переименуйте файл в authorized_keys (например для пользователя alex путь будет выглядеть так:
C:\Users\alex\.ssh\authorized_keys
)
Теперь вы можете использоваться файл id_ed25519 для аутентификации на SFTP сервере в настройках WinSCP (настройки подключения Advanced -> to SSH > Authentication page -> Private key file).
Если вы хотите задать SSH ключ при подключении к SFTP из PowerShell, используйте такую команду:
New-SFTPSession -ComputerName 192.168.13.200 -Credential user1 -KeyFile C:\Users\alex\.ssh\id_ed25519" -Verbose
Windows Server 2019 and Windows 10 (build 1809) have support for OpenSSH out-of-the-box, so there is no need to use any third-party library to run an SSH server or SFTP. In this post, I will demonstrate how to configure an SFTP server in Windows and use it to transfer files.
Contents
- FTPS vs. SFTP
- Install and configure the SFTP server.
- Custom SSH port [optional]
- Allow or deny connections
- Connect to OpenSSH server using SFTP
- Change the default SFTP directory
- Troubleshooting SFTP connections
- Author
- Recent Posts
Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows servers, Active directory, PowerShell, web servers, networking, Linux, virtualization, and Kubernetes. He loves writing for his blog.
FTPS vs. SFTP
The File Transfer Protocol (FTP) is no longer considered safe for use as it lacks the ability to encrypt data while it is in transit. If you still use FTP over a traditional FTP port number (TCP 21), all your data and commands are transmitted in clear text. Anyone can intercept this server–client communication, which is a big security concern as per modern IT standards. Two alternatives to FTP exist:
- FTPS (FTP over SSL/TLS)—This method is just like the traditional FTP with the added support of a TLS certificate to offer encryption.
- SFTP (FTP over SSH)—This method uses SSH for transferring files, which encrypts the communication by default.
Although both can serve the purpose of transferring files, they are totally different by design. FTPS is not very firewall friendly and is difficult to configure. Thus, I will focus on SFTP in this post.
I am using two VMs in a lab environment for this demo:
- Windows Server 2022—This will work as an OpenSSH server.
- Windows 10—This will work as a client.
I have also installed the FileZilla FTP client in a Windows 10 VM, which will connect to the OpenSSH server using the SFTP protocol. Of course, you can use WinSCP or any other FTP client that supports the SFTP protocol.
Install and configure the SFTP server.
First, log in to Windows Server VM and enable the optional OpenSSH feature. To do so, launch an elevated PowerShell console, and run the following command:
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Installing an OpenSSH server in Windows using PowerShell
The installation was successful if the output includes Online : True. The command will automatically configure the required firewall rule, so there is nothing you need to do manually.
Now use the following command to change the startup mode of the OpenSSH server service (sshd) to automatic and start it at the same time:
Get-Service -Name "sshd" | Set-Service -Startup "Automatic" -PassThru | Start-Service -PassThru
Change the service start mode and start the service using PowerShell
You can see that the service is now running. The main configuration file of the OpenSSH server on Windows is %ProgramData%\ssh\sshd_config, but Windows can also read the configuration from the user profile (%UserProfile%\.ssh\config) if available. Furthermore, it allows you to specify a custom configuration file using the -f switch (e.g., sshd.exe -f «c:\users\administrator\.ssh\custom_config»).
Custom SSH port [optional]
By default, the OpenSSH server listens on TCP Port 22. But you can change the port to something else by running the following PS command:
(Get-Content "C:\ProgramData\ssh\sshd_config").replace("#Port 22", "Port 2223") | Set-Content "C:\ProgramData\ssh\sshd_config" Restart-Service "sshd"
Changing the OpenSSH server port on Windows using PowerShell
The first command replaces the port number with the one you specify in the system-wide configuration file (%ProgramData%\ssh\sshd_config), and the second command restarts the service. The following command can be used to make sure the server is now listening on a new port number:
Get-NetTCPConnection -LocalPort 2223 | select Local*, State,` @{n="ProcessName";e={(Get-Process -Id $_.OwningProcess).ProcessName}},` @{n="ProcessPath";e={(Get-Process -Id $_.OwningProcess).Path}} | ft -Auto
Verify the custom port of the OpenSSH server using PowerShell
You can see that the OpenSSH server is now listening on Port 2223.
Allow or deny connections
The OpenSSH server in Windows also lets you control which users or groups are allowed to connect to the server (or denied a connection) using SFTP (and SSH). To do so, you can add the following directives to the configuration file:
- DenyUsers
- AllowUsers
- DenyGroups
- AllowGroups
Note that these directives are processed in the same order as written. By default, the OpenSSH server will allow every local or domain user to connect, but if you want to allow (or deny) a particular user or group, specify that in the configuration file, as shown in this line of code:
AllowGroups testlab\developers testlab\ssh_admins
Remember, these allow or deny directives must come before the Match Group administrators directive, as pointed out in the screenshot; otherwise, it won’t work as expected.
Using the SSH configuration file to allow or deny users and groups
Adding the above line inside the SSH configuration file will allow the members of the developers and ssh_admins groups in the TestLab domain to connect, while denying everyone else. It is recommended to specify the account names in lowercase only. Furthermore, to specify a domain account in UPN format, you must replace the @ character with ? to avoid any conflicts with regular Linux patterns. For example, to specify user@domain.com with an allow or deny directive, you must type it as user?domain*.
Connect to OpenSSH server using SFTP
The OpenSSH server is now set to accept connections from the client. Head over to your Windows 10 machine, launch FileZilla, and make a connection to the server with the settings shown in the screenshot.
Connecting to the SFTP server using the FileZilla FTP client
Make sure the protocol SFTP – SSH File Transfer Protocol and the correct SSH server port are specified. When you connect for the first time, you will see an Unknown host key warning. Click OK to trust the host and continue connecting.
The servers host key is unknown. You have no guarantee that the server is the computer you think it is.
You will now be connected to the server using the SFTP protocol, and you can start transferring files.
Using FileZilla client with the SFTP protocol to transfer files
Change the default SFTP directory
By default, you will land in your user profile directory when you connect to the server. However, you can specify a custom directory in the sshd_config file to change the default root directory for SFTP. To do so, open the C:\ProgramData\ssh\sshd_config file on the server in any text editor, and add the following line:
ChrootDirectory "C:\inetpub\wwwroot"
See the following screenshot for reference:
Change the default SFTP root directory in Windows
Restart the sshd service after making this change, and reconnect the server. You will now land in the specified directory (C:\inetpub\wwwroot). This is particularly useful on web servers, where you want users to land directly inside the website’s root directory instead of their home directory.
FileZilla FTP client connecting to a predefined root directory in Windows
There are many other settings supported by the OpenSSH server, but covering everything is beyond the scope of this article.
Troubleshooting SFTP connections
If you run into any issues while working with OpenSSH server, you can always view the event logs under Applications and Services Logs OpenSSH, as shown in the following screenshot:
Viewing event logs related to OpenSSH in Windows
The OpenSSH server also supports file-based logging, so if you’re interested in that, add the following lines to the SSH configuration file and restart the sshd service.
SyslogFacility LOCAL0 LogLevel Debug3
Enabling file based debug logging using the OpenSSH configuration file
Once you do this, you will be able to view the debug logs in the %ProgramData%\ssh\logs directory. As you can see in the following screenshot, the debug log showed that the user test\john wasn’t able to connect to the server because they are not a member of any group specified in the AllowGroups directive.
Subscribe to 4sysops newsletter!
Viewing OpenSSH debug logs to troubleshoot problems
The procedure described here also allows you to connect to a Windows system using the SSH shell, which means that users who can connect using SFTP can also connect using any SSH client (like putty) and run commands. This is why it is very important to allow only a limited number of groups containing trusted people. I hope this guide helped you get started with SFTP as a safer alternative to an FTP server on Windows.
Introduction
In this tutorial, we will show you how to set up a SFTP server in Windows. If you have a cloud computer with V2 Cloud and you’re looking to setup a secure FTP server in your cloud computer instead, follow this link. The main difference between FTP and SFTP is the security aspect. Running applications that use SFTP for file transfers is the answer to protecting that data in transit.
This tutorial will provide the steps required to set up an SFTP Server using Windows Server 2019’s OpenSSH Server feature. Our SFTP client computer will be a Windows 10 computer, and we will be using Filezilla as the client application to connect to the server.
You can browse the different sections of this tutorial. This is what you need to setup a SFTP server in Windows:
- Configure the SFTP server feature (OpenSSH Server) in Windows Server 2019
- Create the root SFTP directory
- Create the user account that will be used for file transfers
- Install and configure the SFTP client for data transfers
- Perform an SFTP transfer between client and server
Note: the terms “directory” and “file folder” refer to the same object. They are used interoperably in this tutorial.
Section 1: Configure the SFTP server feature (OpenSSH Server) in Windows Server 2019
STEP 1
Login to your server. Then type apps and features in the search bar. Under Apps and Features (the section in the middle of the page), click Manage optional features.
STEP 2
Scroll among the options, find OpenSSH Server, click it, then click Install.
The installation will now begin in the background. We are going to make some changes to the Windows Services to allow for the newly installed OpenSSH server to be started automatically.
STEP 3
Type services in the search bar. Then click the Services Desktop app. Locate the OpenSSH SSH Server option from the list. Right-click it, then select Properties.
STEP 4
Change the Startup type to Automatic. Click Start afterward.
STEP 5
Once the service has started the Service status: will change from Stopped to Running. Click OK to proceed.
STEP 6
Locate the OpenSSH Authentication Agent service. Right-click it, then select Properties.
STEP 7
Repeat Steps 3 to 5 where you will make the same changes as you did with the OpenSSH SSH Server with this service (OpenSSH Authentication Agent).
When done, you’ll notice the status of the two services is now set to Running.
STEP 8
Browse to the following folder, C:\\ProgramData\\ssh in the address bar. You may have to type the location as the ProgramData folder is normally hidden by default. Click the “drop-down arrow” beside Text documents then select All Files. Select sshd_config from the files list, then click Open.
STEP 9
When the sshd_config file opens, click Ctrl+F on your keyboard to launch the Find app. Type “root”, then click Find Next. We are looking for the entry #ChrootDirectory.
STEP 10
Edit the entry to this ChrootDirectory C:\\SFTPRoot. This is the location where our SFTP files will be stored from the server side. Click File then click Save.
Let’s now create the actual folder/root directory we just referenced as our location to save SFTP files.
Section 2: Create the root SFTP directory
STEP 11
Browse to the C:\\ drive on your server. Right-click in any empty space then select New from the drop-down menu then click Folder. Name the folder SFTPRoot. Ensure that it is exactly the same as the folder name referenced in the path in Step 10.
Now let us add the user account on this server that will be used to do the SFTP transfers.
Section 3: Create the user account that will be used for file transfers
STEP 11
Open the Server Manager, then select Tools and click Computer Management.
STEP 12
Click the drop-down arrow beside Local Users and Groups. Click the Users folder. In the middle pane, right-click on any white space and select New User from the drop-down menu.
STEP 13
Create the user account by entering your username and password. Record these credentials as we will be using them for our SFTP transfers. Uncheck the option User must change password at next logon and check the options User cannot change password and Password never expires. Click Create once finished.
Now let us find and record the IP address of our SFTP server. This will be needed along with the username and password we just created for our SFTP connection.
STEP 14
Type cmd at the search bar. Select Command Prompt. Type ipconfig at the prompt then hit the Enter key on your keyboard.
The Ip address of our server is 192.168.50.4.
Our server-side configuration is now complete. We now need to configure our client computer to connect to this newly configured SFTP server and transfer data to it.
Section 4: Install and configure the SFTP client for data transfers
In this example, we will be using Filezilla as our SFTP client. To continue, download the Filezilla client application and install it on your computer. Let’s now create our SFTP site.
STEP 15
Launch the Filezilla app. Click the File option from the menu bar then click Site Manager.
STEP 16
Select the My Sites folder under the left section under Select entry: Then click the New site button.
STEP 17
Name the site, we’ll call it SFTP-Site1. On the General tab in the left section of the Site Manager window, configure the following; Protocol: SFTP – SSH File Transfer Protocol, Host:
192.168.50.4, Port: 22, Logon Type: Normal, User: the User/username that will be used to connect to the SFTP site/server, Password: password for the user. When done click Connect.
STEP 18
Save the password and click OK. Click OK at the Unknown host key pop-up box. Note, you can check the checkbox Always trust the host, add this key to the cache.
Once connected successfully the following will be what you’ll see.
We’ll now proceed to create and configure the remote SFTP directory.
STEP 19
Right-click in any white space in the bottom-right-hand quadrant of the Filezilla GUI window. Then select Create Directory. This will create a file folder in the root SFTP folder on the SFTP server.
STEP 20
Create a name for the new directory, then click OK.
You’ll now see that our newly created directory has been created successfully on our client computer.
If we browse to the SFTPRoot folder on the SFTP server, we’ll see that our directory has been automatically created.
Now that our two sites have been configured. Let’s move on to the final step to perform a secure file transfer.
STEP 21
Select the “source file folder”, from the top left-hand file folder listing with the label Local site: that has the file/files that you want to transfer to your server. Our folder is C:\Users\Kurwin\Downloads\. On the Remote site: select your destination file folder. Locate your file under the bottom-left hand file listings then right-click it and select Upload.
You’ll now see that your file has been transferred successfully.
SFTP server verifies our successful transfer. We see our file in our target directory within our root directory.
That’s it. We have now successfully set up a SFTP server in a Windows environment.
There is a better way to do IT with V2 Cloud
By using V2 Cloud, you get access to a fully-integrated virtual desktop solution, without the traditional complexity of other cloud providers.
There is an easier way to enable secure remote access to employees without sacrificing end-user experience and performance.
V2 Cloud offers a cloud desktop infrastructure with
- No hidden fees
- No complicated setup
- No contracts
- Flat-rate pricing model
We’re the #1 virtualization solution for small businesses. Create virtual desktops, servers, and applications to improve productivity and significantly reduce your IT costs.
Learn more about V2 Cloud and our cloud VDI solution. Get started with a risk-free 7-day trial, and experience the simplicity, scalability and power of V2 Cloud.
Nowadays the process for setting up a SFTP under Windows is fairly simple. But there are still some things that won’t go that easy and will give you strange errors and can cost you a lot of time. Especially when you want to use Active Directory authentication and a network share as the home folder.
First off we have to install OpenSSH. In Windows 10, 11, Windows Server 2019 and Windows 2022 this is just an optional feature that can be selected for installation.
Go to Settings > Apps > Optional features > Add a feature. Select OpenSSH server from the list and click install.
Here you can come across your first hurdle: “Installation failed”.
There is not much to go on here, because “install failed” is all the feedback you’ll get. After checking all kinds of different things, a default GPO was the problem. To solve this you’ll need open gpedit.msc and go to Computer configuration > Administrative Templates > System. And there in the root of System find and open the policy “Specify settings for optional component installation and component repair”.
Enable the setting and also check “Download repair content and optional features directly from Windows Update instead of Windows Server Update Services (WSUS)”.
After this your install of OpenSSH should complete without an error and the binaries will be installed in C:\Windows\System32\OpenSSH.
On older installations you now should make a new rule in Windows Defender Firewall to allow incoming traffic on port 22, but I found that in Windows Server 2022 this is already done.
Now go to the Windows Services and change the OpenSSH Server service from manual to automatic and start the service. When the service is started for the first time the working directory will be created in C:\ProgramData\ssh.
Now that the OpenSSH service is running, you would think that you can connect to it, but when you try, you’ll get an access denied error. This is because you have to specify which accounts have access to the service and by default none are configured.
To configure authentication go to C:\ProgramData\ssh and open the file sshd_config with a text editor. According to the Microsoft documentation (https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_server_configuration#allowgroups-allowusers-denygroups-denyusers), you’ll simply have to add AllowUsers followed by the users you want to grant access to the config file and it should work.
This is the second hurdle in setting up the SFTP server. I tried many combinations of the allowed user syntax, including:DNSdomainname.local\Username
DNSdomainname.local\Username
DNSdomainname.local\Username@Servername
DNSdomainname.local\Username@Servername
NetBIOSdomainname\Username
NetBIOSdomainname\Username
NetBIOSdomainname\Username@Servername
NetBIOSdomainname\Username@Servername
NetBIOSdomainname\Username@172.17.22.10
NetBIOSdomainname\Username@172.17.22.10
NetBIOSdomainname\sa_ftpbackup@Servername
Username?NetBIOSdomainname
Username?NetBIOSdomainname*
Username?DNSdomainname.local
Username?DNSdomainname.local*
But all failed miserably and I got “Access denied” in Putty and “Permission denied, please try again.” in PowerShell.
To get more information about why the access was denied, you can stop the OpenSSH service and start it manually from an elevated prompt with the debug parameter, like: sshd.exe -d
In this logging you’ll see that the group can’t be mached.
debug1: get_passwd: LookupAccountName() failed: 1332.
debug1: Can't match group at line 94 because user NetBIOSdomainname\\username@hostname does not exist
Invalid user NetBIOSdomainname\\username@hostname from x.x.x.x port 53784
debug1: userauth-request for user NetBIOSdomainname\\\\username@hostname service ssh-connection method keyboard-interactive [preauth]
debug1: attempt 1 failures 0 [preauth]
debug1: keyboard-interactive devs [preauth]
debug1: auth2_challenge: user=NetBIOSdomainname\\\\username@hostname devs= [preauth]
debug1: kbdint_alloc: devices '' [preauth]
debug1: userauth-request for user NetBIOSdomainname\\\\username@hostname service ssh-connection method password [preauth]
debug1: attempt 2 failures 1 [preauth]
debug1: Windows authentication failed for user: NOUSER domain: . error: 1326
Failed password for invalid user NetBIOSdomainname\\username@hostname from x.x.x.x port 53784 ssh2
Connection closed by invalid user NetBIOSdomainname\\\\username@hostname x.x.x.x port 53784 [preauth]
Eventually the work-a-round was fairly easy. Create a local group and add your domain users in that local group. Now add that group to the sshd_config file like: AllowGroup SFTPUsers
Now when you try to login, you’ll get a different message “Connection reset by x.x.x.x port 22”. It’s not much, but it is something 😉
Looking at the logging it became clear that the problem had something to do with elevated and privileged processes.
Accepted password for NetBIOSdomainname\\username from x.x.x.x port 53735 ssh2
debug1: monitor_child_preauth: NetBIOSdomainname\\username has been authenticated by privileged process
debug1: monitor_read_log: child log fd closed
debug1: Not running as SYSTEM: skipping loading user profile
CreateProcessAsUserW failed error:1314
fork of unprivileged child failed
debug1: do_cleanup
This can also be solved very easily. Don’t start sshd from the command line, but start the service. The service has to be started under the system account, so it can reach all needed dependencies.
Now that we can access the server over SCP, we only need to alter the default home directory for the users. As long as that is a folder on the server you’re fine, but when you want to use a network location, you’re in for a treat. You can’t use UNC paths.
In the event viewer you’ll see errors like “sshd: error: chroot only support absolute paths”
And “sshd: fatal: chroot (“\\network path”): Operation not supported”
To get around this problem, you could use a symbolic link. Symbolic links or symlinks are “virtual” files or folders which reference a physical file or folder located elsewhere. To create such a symbolic link you have to open an elevated prompt and use the mklink commando. mklink -d <link> <target>
Now you should have a working setup. However, when you get a message stating that permission is denied, you’ll have to add the service account to the local administrators group. This is because of the rights assigned to the symbolic link. By default “Authenticated users”, “System” and “Administrators” are configured, but “Authenticated users only have read rights.
You can’t change these rights. If you try to change them you’ll get enumerating and access denied errors.
So when you add the service account to the local administrators group, you’ll get write rights. So far for the least privileged approach 😉
Started his working life as a system manager at a health care organization. Is now a dedicated technical consultant at PepperByte. Specialist in virtualization and security.
Core qualities
Eager to learn, punctual, fun, loyal, patient
Hobbies
Socializing, watching television series and sports
Job description
Technical Consultant
You can use the built-in OpenSSH package in Windows to easily enable secure file transfers between the client and Windows server using the SFTP (Secure FTP) protocol. In this article, we will show how to install and configure an SFTP server on Windows 10 or Windows Server 2022/2019/2016/2012R2.
Contents:
- How to Install OpenSSH on Windows?
- How to Configure SFTP Server on Windows Using OpenSSH?
- Connecting to SFTP Server Using WinSCP or PowerShell
- Configuring SFTP Public Key Authentication
SFTP (Secure File Transfer Protocol, Secure FTP, or SSH FTP) is the extension of SSH protocol, which is the standard in the world of UNIX/Linux systems. From the user’s point of view, it is similar to FTP, but in fact, it is a completely different protocol, having nothing in common with FTP. Data between the client and the server is transmitted on port 22 through an SSH tunnel (TCP port 22).
The main advantages of SFTP:
- Files and commands are transferred within a secure SSH session;
- One connection is used to send both files and commands;
- Symbolic links, interrupt/resume the transfer, file delete functions, etc. are supported;
- SFTP connection is much faster and more reliable on WAN links where FTP is slow or intermittent;
- Possibility to authenticate using SSH keys.
Do not confuse SFTP and FTPS protocols. FTPS is essentially just a simple FTP with an SSL certificate, and SFTP is the protocol to transfer the FTP data and commands inside the SSH session.
The win32 port of OpenSSH (Win32-OpenSSH) is built into all modern versions of Windows by default. You can use it to configure a secure SFTP server instead of using third-party products like Core FTP, FileZilla, CYGWIN, FTP Shell, IPSwitch, etc.
How to Install OpenSSH on Windows?
The OpenSSH package is a part of the operating system in modern builds of Windows 10 (starting from 1803), Windows 11, and Windows Server 2022/2019 as a Feature on Demand (like RSAT).
On these versions of Windows, you can install the OpenSSH server using PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server*
Or using DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
Also, you can install OpenSSH server from Windows 10 GUI (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).
To check if a package is installed:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
- OpenSSH executables are located in the directory:
c:\windows\system32\OpenSSH\
; - The sshd_config configuration file is located in
C:\ProgramData\ssh
(this directory is created after the first start of the sshd service); - Log file:
c:\windows\system32\OpenSSH\logs\sshd.log
; - The authorized_keys file and keys are stored in a directory:
%USERPROFILE%\.ssh\
.
On the previous earlier builds of Windows 10, Windows 8.1, and on Windows Server 2016/2012 R2, you will have to download Win32-OpenSSH for Windows from GitHub and install it manually (https://github.com/PowerShell/Win32-OpenSSH/releases). We need a version for Windows x64: OpenSSH-Win64.zip (4,15 MB).
- Extract the archive to the target folder: C:\OpenSSH-Win;
- Open an elevated PowerShell prompt and switch to the OpenSSH folder:
Cd C:\OpenSSH-Win
- Add the path to the OpenSSH directory to the Path environment variable (System Properties -> Advanced tab -> Environment Variables -> Select and edit the Path system variable -> Add the path to the OpenSSH folder);
- Install the OpenSSH server:
.\install-sshd.ps1
(a green message should appear “sshd and ssh-agent services successfully installed”);If running PowerShell scripts on your computer is blocked by your PowerShell Execution Policy, you can run the script with this command:
powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1
How to Configure SFTP Server on Windows Using OpenSSH?
Now you need to configure OpenSSH on Windows for SFTP mode.
Enable autostart for the SSHD service and start it using the following PowerShell service management commands:
Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd
Use the PowerShell to open TCP port 22 in the Windows Firewall for incoming SSH traffic:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
Note. The previous command won’t work in old desktop Windows versions. In this case, another command is used: netsh advfirewall firewall add rule name='SSH Port' dir=in action=allow protocol=TCP localport=22
Open the SSHD configuration file (C:\ProgramData\SSH\sshd_config
) in any text editor. Find and check the value of the Subsystem sftp directive. The sftp-server.exe file should be specified here.
You can additionally configure the following parameters in the sshd_config configuration file:
# only allow users in this domain group to connect to OpenSSH AllowGroups corp\sftp_users # enable password authentication (SSH keys cannot be used) AuthenticationMethods password #default (chrooot) directory for SFTP users (by default, the user connects to the directory with his profile in the C:\users\username folder) ChrootDirectory C:\SFTP ForceCommand internal-sftp #You can set an individual chrootdirectory for each user: Match User abrown ChrootDirectory c:\SFTP\abrown ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no Match User jsmith ChrootDirectory c:\SFTP\jsmith ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
Connecting to SFTP Server Using WinSCP or PowerShell
Now you can connect to your Windows SSH server using the SFTP protocol. Next, we’ll show you how to connect to an SFTP server using the free WinSCP client, the PowerShell console, and the built-in sftp.exe tool.
In the connection configuration window, select the SFTP as the file transfer protocol, specify the server name and the credentials of the Windows account (use the user@domain
format for domain users), which is used for connection (it is also possible to configure public key authentication).
When you try to connect for the first time, the following notification of the host key not found in the local cache appears.
If everything is configured correctly, a client should connect to the SFTP server and display the list of files in the user’s home chroot directory (by default, it is the user’s profile directory).
Using the familiar file manager interface (like Total Commander), you can copy files between the server and the client using the secure SFTP protocol.
You can use the Posh-SSH module to connect to an SFTP server from PowerShell. You can download and install the module from the PowerShell Gallery or offline:
Install-Module -Name Posh-SSH
To connect to the SFTP server using a password, you need to get the username and password via Get-Credential:
$usrCreds= Get-Credential
Now you can connect to your SFTP server:
$SFTPSession = New-SFTPSession -ComputerName 192.168.3.20 -Credential $usrCreds
Now you can list the files in the remote directory on the SFTP server. In this example, I will get a list of files on the user’s Desktop (the user’s profile will be the root user folder/chroot in this case)
Get-SFTPChildItem -SFTPSession $SFTPSession -Path "desktop" –Recurse
Download a file from a remote SFTP server:
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path "desktop/OpenVPNScript.log" -Destination c:\PS
To upload a file from your computer to a remote SFTP host:
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:\PS\mytestfile.log -Destination "desktop"
Close the SFTP session:
Remove-SFTPSession -SFTPSession $SFTPSession
On Windows, you can use the built-in sftp.exe console command (installed with the OpenSSH client) to connect to an SFTP server.
Connect to sftp server:
sftp [email protected]
Connect using ssh private key:
sftp -i .ssh/id_rsa [email protected]
List files in a remote directory:
pwd
Download the file from SFTP to a local directory on your computer:
get download_this_file_from_sftp.txt
Upload a file from your computer to an SFTP server:
put file_to_uplodad.txt
Close session:
exit
Configuring SFTP Public Key Authentication
You can enable SFTP key-based authentication in Windows. In this case, you can authenticate to the SFTP server without entering a password.
- Create SSH keys on your computer (SFTP client) for the user under which you will connect to the server:
ssh-keygen -t ed25519
- The ssh-keygen tool will generate two files id_ed25519 (private key for the client computer) and id_ed25519.pub (public key for the SFTP server);
- Now you need to add your SSH key to the Windows server (SFTP host). Copy the file id_ed25519.pub (or id_rsa.pub depending on the key type) to the .ssh directory of the user profile under which you will connect to the SFTP. Rename the file to authorized_keys (for example, the following key file is used for the user
max1
:C:\Users\max1\.ssh\authorized_keys
)
Now you can use the id_ed25519
file to authenticate on the SFTP server. You can set your key in the WinSCP settings (Advanced -> to SSH connection settings > Authentication page -> Private key file).
If you want to use an SSH key when connecting to SFTP from PowerShell, use the following command:
New-SFTPSession -ComputerName 192.168.3.20 -Credential remoteuser1 -KeyFile C:\Users\max1\.ssh\id_ed25519" -Verbose