Настройка openssh windows server 2019 allowgroups

Raymii.org

SSH on Windows Server 2019 (including how to sudo)

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

Table of Contents

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:

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

Example output for both:

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.

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

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:

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:

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:

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:

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:

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.

Читайте также:  Доклад что такое windows

Create the folder where the authorized_keyfile belongs:

Use scp to copy the public key file generated previously:

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

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

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:

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:

PermitRootLogin on Windows

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

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:

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

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:

Interactive shell example:

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

Установка OpenSSH для Windows Server 2019 и Windows 10 Installation of OpenSSH For Windows Server 2019 and Windows 10

Клиент OpenSSH и сервер OpenSSH являются отдельными устанавливаемыми компонентами в Windows Server 2019 и Windows 10 1809. The OpenSSH Client and OpenSSH Server are separately installable components in Windows Server 2019 and Windows 10 1809. Пользователи с этими версиями Windows могут установить и настроить OpenSSH, используя приведенные ниже инструкции. Users with these Windows versions should use the instructions that follow to install and configure OpenSSH.

Пользователи, которые получили OpenSSH из репозитория PowerShell на сайте GitHub (https://github.com/PowerShell/OpenSSH-Portable) должны использовать инструкции из репозитория, а не эти инструкции. Users who acquired OpenSSH from the PowerShell GitHub repo (https://github.com/PowerShell/OpenSSH-Portable) should use the instructions from there, and should not use these instructions.

Читайте также:  Csv кодировка mac os

Установка OpenSSH через пользовательский интерфейс настройки в Windows Server 2019 или Windows 10 версии 1809 Installing OpenSSH from the Settings UI on Windows Server 2019 or Windows 10 1809

Клиент и сервер OpenSSH устанавливаются в Windows 10 версии 1809 как отдельные компоненты. OpenSSH client and server are installable features of Windows 10 1809.

Чтобы установить OpenSSH, откройте раздел Параметры и последовательно выберите Приложения > Приложения и возможности > Управление дополнительными компонентами. To install OpenSSH, start Settings then go to Apps > Apps and Features > Manage Optional Features.

Просмотрите этот список и выясните, установлен ли клиент OpenSSH. Scan this list to see if OpenSSH client is already installed. Если нет, то выберите пункт Добавить компонент в верхней части страницы, а затем: If not, then at the top of the page select «Add a feature», then:

  • чтобы установить клиент OpenSSH, найдите элемент Клиент OpenSSH и щелкните Установить; To install the OpenSSH client, locate «OpenSSH Client», then click «Install».
  • чтобы установить сервер OpenSSH, найдите элемент Сервер OpenSSH и щелкните Установить. To install the OpenSSH server, locate «OpenSSH Server», then click «Install».

После завершения установки вернитесь в раздел Приложения > Приложения и возможности > Управление дополнительными компонентами, где теперь должны появиться компоненты OpenSSH. Once the installation completes, return to Apps > Apps and Features > Manage Optional Features and you should see the OpenSSH component(s) listed.

Установка сервера OpenSSH создаст и включит правило брандмауэра с именем OpenSSH-Server-in-TCP. Installing OpenSSH Server will create and enable a firewall rule named «OpenSSH-Server-In-TCP». Правило разрешает входящий трафик SSH через порт 22. This allows inbound SSH traffic on port 22.

Установка OpenSSH с помощью PowerShell Installing OpenSSH with PowerShell

Чтобы установить OpenSSH с помощью PowerShell, запустите PowerShell от имени администратора. To install OpenSSH using PowerShell, first launch PowerShell as an Administrator. Убедитесь, что функции OpenSSH доступны для установки, выполнив следующие действия. To make sure that the OpenSSH features are available for install:

Затем установите компонент сервера и (или) клиента. Then, install the server and/or client features:

Удаление OpenSSH Uninstalling OpenSSH

Чтобы удалить OpenSSH через раздел Параметры в ОС Windows, откройте этот раздел и последовательно выберите Приложения > Приложения и возможности > Управление дополнительными компонентами. To uninstall OpenSSH using the Windows Settings, start Settings then go to Apps > Apps and Features > Manage Optional Features. В списке установленных компонентов выберите компонент Клиент OpenSSH или Сервер OpenSSH и щелкните Удалить. In the list of installed features, select the OpenSSH Client or OpenSSH Server component, then select Uninstall.

Чтобы удалить OpenSSH с помощью PowerShell, выполните одну из следующих команд: To uninstall OpenSSH using PowerShell, use one of the following commands:

После удаления OpenSSH может потребоваться перезагрузка Windows, если служба использовалась в момент удаления. A Windows restart may be required after removing OpenSSH, if the service is in use at the time it was uninstalled.

Начальная настройка сервера SSH Initial Configuration of SSH Server

Чтобы настроить только что установленный сервер OpenSSH для использования в ОС Windows, запустите PowerShell от имени администратора и выполните следующие команды, чтобы запустить службу SSHD: To configure the OpenSSH server for initial use on Windows, launch PowerShell as an administrator, then run the following commands to start the SSHD service:

Начальное использование SSH Initial use of SSH

После установки сервера OpenSSH в Windows вы можете быстро проверить его работу с помощью PowerShell на любом устройстве Windows, где установлен клиент SSH. Once you have installed the OpenSSH Server on Windows, you can quickly test it using PowerShell from any Windows device with the SSH Client installed. В PowerShell запустите следующую команду: In PowerShell type the following command:

Первое подключение к любому серверу сопровождается сообщением примерно такого содержания: The first connection to any server will result in a message similar to the following:

В качестве ответа принимаются значения yes (да) или no (нет). The answer must be either «yes» or «no». Ответ «Да» приведет к добавлению этого сервера в список известных узлов SSH в локальной системе. Answering Yes will add that server to the local system’s list of known ssh hosts.

После этого появится запрос на ввод пароля. You will be prompted for the password at this point. В целях безопасности пароль не будет отображаться по мере ввода. As a security precaution, your password will not be displayed as you type.

После успешного подключения вы увидите командную оболочку, которая выглядит примерно так: Once you connect you will see a command shell prompt similar to the following:

Читайте также:  Управление кэшем windows 10

По умолчанию для сервера OpenSSH в ОС Windows используется командная оболочка Windows. The default shell used by Windows OpenSSH server is the Windows command shell.

OpenSSH Server Configuration for Windows 10 1809 and Server 2019

This topic covers the Windows-specific configuration for OpenSSH Server (sshd).

OpenSSH maintains detailed documentation for configuration options online at OpenSSH.com, which is not duplicated in this documentation set.

Configuring the default shell for OpenSSH in Windows

The default command shell provides the experience a user sees when connecting to the server using SSH. The initial default Windows is the Windows Command shell (cmd.exe). Windows also includes PowerShell and Bash, and third party command shells are also available for Windows and may be configured as the default shell for a server.

To set the default command shell, first confirm that the OpenSSH installation folder is on the system path. For Windows, the default installation folder is SystemDrive:WindowsDirectory\System32\openssh. The following commands shows the current path setting, and add the default OpenSSH installation folder to it.

Command shell Command to use
Command path
PowerShell $env:path

Configuring the default ssh shell is done in the Windows registry by adding the full path to the shell executable to Computer\HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH in the string value DefaultShell.

As an example, the following Powershell command sets the default shell to be PowerShell.exe:

Windows Configurations in sshd_config

In Windows, sshd reads configuration data from %programdata%\ssh\sshd_config by default, or a different configuration file may be specified by launching sshd.exe with the -f parameter. If the file is absent, sshd generates one with the default configuration when the service is started.

The elements listed below provide Windows-specific configuration possible through entries in sshd_config. There are other configuration settings possible in that are not listed here, as they are covered in detail in the online Win32 OpenSSH documentation.

AllowGroups, AllowUsers, DenyGroups, DenyUsers

Controlling which users and groups can connect to the server is done using the AllowGroups, AllowUsers, DenyGroups and DenyUsers directives. The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups. All account names must be specified in lower case. See PATTERNS in ssh_config for more information on patterns for wildcards.

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 conflict with standard Linux patterns. For that reason, * is added to cover FQDNs. Also, this approach uses «?», instead of @, to avoid conflicts with the username@host format.

Work group users/groups and internet-connected accounts are always resolved to their local account name (no domain part, similar to standard Unix names). Domain users and groups are strictly resolved to NameSamCompatible format — domain_short_name\user_name. All user/group based configuration rules need to adhere to this format.

Examples for domain users and groups

Examples for local users and groups

AuthenticationMethods

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

AuthorizedKeysFile

The default is «.ssh/authorized_keys .ssh/authorized_keys2». If the path is not absolute, it is taken relative to user’s home directory (or profile image path). Ex. c:\users\user. Note that if the user belongs to the administrator group, %programdata%/ssh/administrators_authorized_keys is used instead.

ChrootDirectory (Support added in v7.7.0.0)

This directive is only supported with sftp sessions. A remote session into cmd.exe wouldn’t honor this. To setup a sftp-only chroot server, set ForceCommand to internal-sftp. You may also set up scp with chroot, by implementing a custom shell that would only allow scp and sftp.

HostKey

The defaults are %programdata%/ssh/ssh_host_ecdsa_key, %programdata%/ssh/ssh_host_ed25519_key, %programdata%/ssh/ssh_host_dsa_key, and %programdata%/ssh/ssh_host_rsa_key. If the defaults are not present, sshd automatically generates these on a service start.

Match

Note that pattern rules in this section. User and group names should be in lower case.

PermitRootLogin

Not applicable in Windows. To prevent administrator login, use Administrators with DenyGroups directive.

SyslogFacility

If you need file based logging, use LOCAL0. Logs are generated under %programdata%\ssh\logs. For any other value, including the default value, AUTH directs logging to ETW. For more info, see Logging Facilities in Windows.

Not supported

The following configuration options are not available in the OpenSSH version that ships in Windows Server 2019 and Windows 10 1809:

  • AcceptEnv
  • AllowStreamLocalForwarding
  • AuthorizedKeysCommand
  • AuthorizedKeysCommandUser
  • AuthorizedPrincipalsCommand
  • AuthorizedPrincipalsCommandUser
  • Compression
  • ExposeAuthInfo
  • GSSAPIAuthentication
  • GSSAPICleanupCredentials
  • GSSAPIStrictAcceptorCheck
  • HostbasedAcceptedKeyTypes
  • HostbasedAuthentication
  • HostbasedUsesNameFromPacketOnly
  • IgnoreRhosts
  • IgnoreUserKnownHosts
  • KbdInteractiveAuthentication
  • KerberosAuthentication
  • KerberosGetAFSToken
  • KerberosOrLocalPasswd
  • KerberosTicketCleanup
  • PermitTunnel
  • PermitUserEnvironment
  • PermitUserRC
  • PidFile
  • PrintLastLog
  • RDomain
  • StreamLocalBindMask
  • StreamLocalBindUnlink
  • StrictModes
  • X11DisplayOffset
  • X11Forwarding
  • X11UseLocalhost
  • XAuthLocation

—>

Оцените статью