Настройка firewall windows server 2016 rdp

Далее будут рассмотрены пять мер, позволяющих существенно повысить безопасность RDP в Windows 2016. В статье предполагается, что сервер терминалов уже прошел предварительную настройку и работает. Все скриншоты соответствуют Windows Server 2016.

Далее будут рассмотрены пять мер, позволяющих существенно повысить безопасность RDP в Windows 2016. В статье предполагается, что сервер терминалов уже прошел предварительную настройку и работает. Все скриншоты соответствуют Windows Server 2016.

Смена стандартного порта Remote Desktop Protocol

Начнем со стандартной меры — смены стандартного порта Windows 2016 RDP, что позволит предотвратить атаку всем известных портов (well-known ports).
Настройку порта можно осуществить с помощью реестра — HKEY_LOCAL_MACHINESystemCurrentControlSetControlTerminalServerWinStationsRDP-TcpPortNumber.

Рис. 1. Смена порта RDP в Windows Server 2016 с помощью редактора реестра

После этого запустите Брандмауэр Windows и на боковой панели слева выберите Дополнительные параметры. Далее — Правила для входящих соединений и нажмите кнопку Создать правило (на панели справа)

Рис. 2. Правила для входящих подключений

В появившемся окне выберите Для порта и нажмите кнопку Далее. Затем выберите Определенные локальные порты и введите порт, указанный при редактировании реестра (рис. 3). В следующем окне мастера нужно выбрать Разрешить подключение(рис. 4).

Рис. 3. Задаем новый порт

Рис. 4. Разрешаем подключение

Собственно, на этом настройка завершена. Отключитесь от сервера и установите новое соединение. Не забудьте в настройках RDP-клиента Windows Server 2016 указать новый порт: IP-адрес_сервера: порт.

Блокируем учетные записи с пустым паролем

Усилить RDP безопасность можно, запретив windows server подключаться учетным записям с пустым паролем. Для этого нужно включить политику безопасности «Учетные записи: разрешить использование пустых паролей только при консольном входе»:

  1. Откройте локальную политику безопасности (нажмите Win + R и введите команду secpol.msc)
  2. Перейдите в раздел Локальные политики, Параметры безопасности
  3. Дважды щелкните на нужной нам политике и убедитесь, что для нее задано значение Включен (рис. 5).

Рис. 5. Включение политики безопасности в Windows 2016 RDP «Учетные записи: разрешить использование пустых паролей только при консольном входе»

Настраиваем политику блокировки

Основная проблема в том, что по умолчанию Windows-server (даже 2016!) не защищен от брутфорса, поэтому безопасность RDP в Windows 2016 пребывает не на очень высоком уровне. При наличии какого-либо сервиса, в частности, FTP, вас могут брутфорсить, пока не получат доступ к системе, перебирая огромное множество логинов и паролей. Именно поэтому необходима настройка временной блокировки пользователя после нескольких неудачных попыток.

Необходимый набор правил и настроек называется Политика блокировки учетной записи (Account Lockout Policy). Пока вы еще не закрыли окно Локальная политика безопасности, перейдите в раздел Политики учетных записей, Политика блокировки учетной записи. Установите Пороговое значение блокировки — 5 (максимум 5 неудачных попыток входа), Продолжительность блокировки учетной записи — 30 (на 30 минут учетная запись будет заблокирована после 5 неудачных попыток входа).

Рис. 6. Настройка политики блокировки учетной записи

Настройка службы шлюза служб терминалов

Служба «Шлюз TS (служб удаленных рабочих столов)» Windows Server 2016 разрешает сторонним пользователям реализовывать удаленное подключение к терминальным серверам и другим машинам частной сети с активированным протоколом удаленного рабочего стола. Служба обеспечивает RDP безопасность подключений за счет использования протокола HTTPS/SSL, что позволяет не заниматься настройкой VPN для шифрования трафика.

Служба позволяет контролировать доступ к машинам, устанавливая правила авторизации и требования к удаленным пользователям. Администратор сможет контролировать пользователей, которые могут подключаться к внутренним сетевым ресурсам, сетевые ресурсы, к которым могут подключаться пользователи, определять, должны ли клиентские компьютеры быть членами групп Active Directory и др.

Порядок действий для установки службы «Шлюз ТS»:

  1. Откройте Диспетчер серверов и на главной его странице нажмите ссылку Добавить роли и компоненты
  2. Нажмите Далее, а затем выберите Установка ролей или компонентов.
  3. Выберите ваш сервер из пула серверов
  4. Выберите Службы удаленных рабочих столов и нажмите Далее несколько раз, пока не достигнете страницы Выбор служб ролей
  5. Выберите службы ролей Шлюз удаленных рабочих столов (рис. 7)
  6. Нажмите кнопку Добавить компоненты
  7. Нажимайте Далее для завершения процедуры установки. Когда все будет готово для установки выбранных компонентов, нажмите кнопку Установить (рис. 8).

Рис. 7. Установка службы ролей

Рис. 8. Все готово для установки

Далее нужно создать сертификат для шлюза служб удаленных рабочих столов. Запустите Диспетчер служб IIS, выберите пункт Сертификаты сервера. На панели справа выберите Создать сертификат домена. Введите необходимые сведения (рис. 11).

Рис. 9. Диспетчер служб IIS

Рис. 10. Выберите Создать сертификат домена

Рис. 11. Информация о сертификате

Далее нужно выбрать центр сертификации, который подпишет сертификат, и нажать кнопку Готово. Сертификат появится в списке сертификатов.

Следующий шаг — настройка шлюза TS на использование сертификата. Вернитесь к Диспетчеру серверов и, используя меню Средства, запустите Диспетчер шлюза удаленных рабочих столов. Обратите внимание, что есть одна ошибка — Сертификат сервера еще не установлен или не выбран. Собственно, все, что остается сделать — нажать ссылку рядом Просмотр и изменение свойств сертификата и выбрать ранее созданный сертификат, нажав кнопку Импорт сертификата (рис. 13). В этом окне также можно создать самозаверяющийся сертификат.

Рис. 12. Диспетчер шлюза удаленных рабочих столов

Рис. 13. Выбор сертификата SSL

Используем протокол SSL/TLS для защиты RDP

Если соединение с RDP-сервером реализовывается не через VPN, для обеспечения защиты подключений рекомендуется активировать SSL/TLS-туннелирование соединения.

Опцию RDP через TLS можно активировать через набор правил и настроек защиты сервера удаленных рабочих столов. Введите команду gpedit.msc и перейдите в раздел Конфигурация компьютера, Административные шаблоны, Компоненты Windows, Службы удаленных рабочих столов, Узел сеансов удаленных рабочих столов, Безопасность. Откройте политику Требовать использования специального уровня безопасности для удаленных подключений по протоколу RDP. Выберите значение Включено и выберите уровень безопасности SSL (рис. 14).

Рис. 14. Включение RDP через TLS

На этом настройка безопасности RDP Windows server 2016 закончена.

  • Remove From My Forums
  • Question

  • I’m having trouble getting RDP to work on an alternative port.  I believe the firewall rules need to be updated and thats where I’m stuck.  Does anyone know of a link that describes all the steps?

    I found older articles that describe updating the port in the registry which I tried.  After reboot I was not able to access the server on that port.  There are firewall rules for RDP but they cannot be modified (or I don’t know how). 

    My server is just a stand-alone server, so, no domain controller or group policy objects.  Just a clean install of WS2016.

    If the registry change is all thats needed I’ll have to dig deeper into why it didn’t work.

Answers

  • Hi,

    You can create the necessary Inbound Rules using Windows Firewall with Advanced Security (wf.msc), or via command line.  For example, say you plan to change the listening port to 40012.  In administrator command prompt you could run the following
    commands:

     
    netsh advfirewall firewall add rule name="Remote Desktop (TCP-In) 40012" dir=in localport=40012 protocol=tcp action=allow
    netsh advfirewall firewall add rule name="Remote Desktop (UDP-In) 40012" dir=in localport=40012 protocol=udp action=allow
     

    The above will create two new inbound rules, one for TCP and the other UDP, to allow incoming RDP traffic on your new port (40012 in the example).  You still need to change the listening port in the registry.

    -TP

    • Marked as answer by

      Thursday, March 9, 2017 9:40 PM

Протокол Remote Desktop Protocol (RDP) позволяет удаленно подключиться к рабочему столу компьютера с Windows и работать с ним, как будто это ваш локальный компьютер. По умолчанию RDP доступ в Windows запрещен. В этой статье, мы покажем, как включить и настроить RDP доступ в Windows 10 и Windows Server 2016/2019.

Содержание:

  • Включаем удаленный рабочий стол в Windows 10
  • Как включить RDP доступ с помощью PowerShell?
  • RDP доступ к Windows Server 2016/2019
  • Включение RDP с групповых политик в домене Active Direcrtory
  • Как удаленно включить RDP на компьютере Windows?

Включаем удаленный рабочий стол в Windows 10

Самый простой способ включить RDP доступ в Windows – воспользоваться графическим интерфейсом.

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

SystemPropertiesRemote

Перейдите на вкладку Remote Settings (Удаленный доступ), включите опцию Allow remote connection to this computer (Разрешить удалённые подключения к этому компьютеру).

В целях безопасности желательно разрешить подключение только с клиентов RDP с поддержкой протокола NLA (Allow connections only from computers running Remote Desktop with Network Level Authentication/ Разрешить подключение только с компьютеров, на которых работает удаленный рабочий стол с проверкой подлинности на уровне сети).

включить RDP доступ к Windows 10 из панели управления

Сохраните изменения, нажав ОК.

По умолчанию право на подключение к компьютеру через RDP есть только у членов группы локальных администраторов. Если вам нужно разрешить RDP доступ другим пользователям, нажмите кнопку Select Users.

разрешить пользователям подключаться по RDP

Все пользователи, которых вы укажете здесь будет добавлены в локальную группу Remote Desktop Users. Вы можете в командной строке вывести список пользователей в этой группе:

net localgroup "Remote Desktop Users"

или

net localgroup “Пользователи удаленного рабочего стола”

список пользователей в группе Remote Desktop Users

Чтобы добавить нового пользователя в группу доступа RDP, выполните:

net localgroup "Remote Desktop Users" /add publicuser

В русской версии Windows измените название группы на “Пользователи удаленного рабочего стола”.

В новых билдах Windows 10 классическая панель для включения RDP доступа теперь спрятана и Microsoft рекомендует пользоваться новой панелью Setting.

  1. Перейдите в Settings -> System —> Remote Desktop;
  2. Включите опцию Enable Remote Desktop; включить Remote Desktop в новой панели управления Windows 10 2004
  3. Подтвердите включение RDP на компьютере.

Обратите внимание, что вы не можете включить RDP доступ к редакции Windows 10 Home. RDP сервер работает только на Windows 10 Pro и Enterprise. Впрочем, есть обходное решение.

Обратите внимание, что по умолчанию при включении Remote Desktop, включаются две опции:

  • Keep my PC awake for connection when it is plugged in ;
  • Make my PC discoverable on private networks to enable automatic connection from a remote device

На жмите на ссылку “Advanced settings”. Здесь можно включить использование протокола “Network Level Authentication” для RDP подключений (рекомендуется).

RDP включить доступ по NLA

Если на компьютере включен Windows Defender Firewall (брандмауэр), то нужно проверить, что в нем разрешены входящие RDP подключения. По умолчанию для RDP подключений используется порт TCP
3389
, а в последних билдах Windows также используется
UDP 3389
( см. статью про кейс с черным экраном вместо рабочего стола при RDP доступе).

Перейдите в панель управления и выберите элемент Windows Defender Firewall. Откройте список стандартных правил брандмауэра Windows, щелкнув в левом столбце по ссылке Allow an app or feature through Windows Firewall.

настройки Windows Defender Firewall

Проверьте, что правило Remote Desktop включено для профиля Private (домашняя или рабочая сеть) и, если необходимо, для профиля Public (общедоступные сети).

разрешить входящие rdp подключения в windows defender firewall

Подробнее про типы сетей и профили брандмауэра Windows здесь.

Если нужно, вы можете дополнительно ограничить длительность RDP сессий с помощью GPO.

Теперь к данному компьютеру можно подключится с помощью RDP клиента. Встроенный RDP клиент Windows –
mstsc.exe
. Он сохраняет всю историю RDP подключений с компьютера. Поддерживается копирование файлов между локальным и удаленным компьютером прямо через буфер обмена RDP.

Также вы можете использовать менеджеры RDP подключений, такие как RDCMan или mRemoteNG, или альтернативные клиенты.

mstsc.exe стандартный rdp клиент windows

Для удобства пользователей пароль для RDP подключения можно сохранить в Windows Credential Manager.

Как включить RDP доступ с помощью PowerShell?

Вы можете включить RDP доступ в Windows с помощью пары PowerShell команд. Это гораздо быстрее:

  1. Запустите консоль PowerShell.exe с правами администратора;
  2. Включите RDP доступ в реестре с помощью командлета Set-ItemProperty:
    Set-ItemProperty -Path 'HKLM:SystemCurrentControlSetControlTerminal Server' -name "fDenyTSConnections" -value 0

    Чтобы закрыть RDP доступ, измените значение fDenyTSConnections на 1.

  3. Разрешите RDP подключения к компьютеру в Windows Defender Firewall. Для этого включите предустановленное правило :
    Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
    включить rdp в windows с помощью powershell
  4. Если нужно добавить пользователя в группу в локальную группу RDP доступа, выполните:
    Add-LocalGroupMember -Group "Remote Desktop Users" -Member 'a.petrov'

Чтобы проверить, что на компьютере открыт RDP порт, воспользуйтесь командлетом Test-NetConnection:

Test-NetConnection -ComputerName deskcomp323 -CommonTCPPort rdp

проверить, что на компьютере открыт rdp порт 3389

RDP доступ к Windows Server 2016/2019

В отличии от десктопной редакции Windows 10, в Windows Server по умолчанию поддерживается два одновременных RDP подключения. Эти подключения используются администраторами для управления сервером.

Включается RDP в Windows Server аналогично. Через SystemPropertiesRemote, через Server Manager или командами PowerShell, рассмотренными выше.

включить remote desktop в windows server 2019

Вы можете использовать Windows Server в качестве терминального сервера. В этом случае множество пользователей могут одновременно подключаться к собственному рабочему столу на сервере. Для этого нужно установить и настроить на сервере роль Remote Desktop Session Host. Это требует приобретения специальных RDS лицензии (CAL). Подробнее о RDS лицензировании здесь.

роль Remote Desktop Session Host

Для дополнительно защиты RDP сессий можно использовать SSL/TLS сертификаты.

Включение RDP с групповых политик в домене Active Direcrtory

Если вам нужно включить RDP доступ сразу на большом количестве компьютеров, можно воспользоваться групповыми политиками (GPO). Мы подразумеваем, что все компьютеры включены в домен Windows.

  1. Запустите консоль управления доменными GPO
    gpmc.msc
    ;
  2. Создайте новую (или отредактируйте уже существующую) групповую политику и привяжите ее к целевой OU с компьютерами или серверами; создать GPO для включения RDP на компьютерах и серверах домена
  3. Переключитесь в режим редактирования политики и перейдите в секцию GPO Computer Configuration -> Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Session Host -> Connections;
  4. Найдите и включите политику Allow Users to connect remotely by using Remote Desktop Services, установив ее в Enable; групповая политика Allow Users to connect remotely by using Remote Desktop Services
  5. Обновите параметры групповых политик на клиентах;
  6. После применения данной политики вы сможете подключится ко всем компьютерам по RDP (политика применится как к десктопным клиентам с Windows 10, так и к Windows Server). Если нужно, вы можете более тонко нацелить политики на компьютеры с помощью WMI фильтров GPO.
  7. Если на компьютерах включен Windows Defender Firewall, нужно в этой же GPO разрешить RDP-трафик для доменного профиля. Для этого нужно активировать правило Windows Firewall: Allow inbound Remote Desktop Exceptions (находится в разделе Computer Configuration -> Administrative Templates -> Network -> Network Connections -> Windows Firewall -> Domain Profile). параметр GPO для разрешения RDP трафика - Windows Firewall: Allow inbound Remote Desktop Exceptions

    Подробнее о настройке правил брандмаура Windows через GPO рассказано здесь.

Как удаленно включить RDP на компьютере Windows?

Также вы можете удаленно включить RDP на любом компьютере Windows. Для этого у вас должен быть удаленный доступ к этому компьютеру (через PowerShell или WMI) и ваша учетная запись состоять в группе локальных администраторов на этом компьютере.

Вы можете удаленно включить RDP через реестр. Для этого на удаленном компьютере должна быть включена служба Remote Registry (по умолчанию она отключена). Чтобы запустить службу:

  1. Запустите консоль управления службами (
    services.msc
    );
  2. Выберите Connect to another computer и укажите имя удаленного компьютера; подключиться к службам на удаленом компьютере
  3. Найдите в списке службу Remote Registry, измените тип запуска на Manual (ручной) и затем запустите службу – Start. включить службу remote registry

Тоже самое можно выполнить удаленно из командной строки с помощью встроенной утилиты
sc
(позволяет создавать, управлять или удалять службы Windows):

sc \WKMDK22SQ65 config RemoteRegistry start= demand
sc \WKMDK22SQ65 start RemoteRegistry

sc - включить службу RemoteRegistry из командной строки

Затем на локальном компьютере

  1. Запустите редактор реестра
    regedit.exe
  2. Выберите в меню Файл пункт Connect Network Registry (Подключить сетевой реестр)
  3. Укажите имя или IP адрес удаленного компьютера, на котором нужно включить службу RDP;
  4. Перейдите в раздел
    HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlTerminal Server
    ;
  5. Найдите параметр fDenyTSConnections (тип REG_DWORD). Если данный ключ отсутствует – создайте его. Измените его значение на 0, чтобы включить RDP. fDenyTSConnections - параметр реестра для включения rdp в windows

    Для отключения RDP доступа нужно изменить значение fDenyTSConnections на 1.

Сразу после этого без перезагрузки удаленный компьютер должен стать доступным по RDP.

Но гораздо быстрее можно включить RDP в реестре удаленого компьютера через командную строку:

REG ADD "\WKMDK22SQ65HKLMSYSTEMCurrentControlSetControlTerminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

Если на удаленном компьютере настроен PowerShell remoting, вы можете выполнить на нем удаленную команду через Invoke-Command:

Invoke-Command -Computername WKMDK22SQ65 -ScriptBlock {Set-ItemProperty -Path "HKLM:SystemCurrentControlSetControlTerminal Server" -Name "fDenyTSConnections" –Value 0}

Если в Windows установлен OpenSSH сервер, вы можете подключиться к нему любым ssh клиентом и внести изменения в реестр в локальной ssh сессии.

Также вы можете подключиться к удаленному компьютеру и включить RDP через WMI:

$compname = “WKMDK22SQ65”
(Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace rootCIMV2TerminalServices -Computer $compname -Authentication 6).SetAllowTSConnections(1,1)

разрешить rdp в windows удаленно через wmi

Remote Desktop Protocol (RDP) is a Microsoft-proprietary remote access protocol that is used by Windows systems administrators to manage Windows Server systems remotely. What sets RDP apart from, say, Windows PowerShell or Secure Shell (SSH) remoting is the presence of the full graphical desktop, as shown in Figure 1.

MORE: Best Remote Access Software and Solutions

By default, the RDP server component listens for incoming connections on TCP port 3389 by default, although this can be changed by the administrator for security reasons.

To be sure, Microsoft’s current push is for admins to reduce their reliance upon RDP and instead (a) deploy Windows Servers in Server Core or Nano mode; and (b) employ Windows PowerShell command-line remote administration instead of RDP.

Microsoft’s justification for this advice is two-fold:

  • A GUI layer consumes unnecessary system resources
  • A GUI layer broadens the attack surface of your servers

Regardless, many admins are accustomed to RDP-based remote administration, and seek to do so even in the newly released Windows Server 2016 operating system. Let’s learn how to enable RDP in Server 2016 (tl;dr: the process is identical to Windows Server 2012 R2).

Server Manager

Open the Server Manager console, navigate to the Local Server node, and click the Remote Desktop hyperlink as shown in Figure 2.

The Remote Desktop hyperlink is simply a shortcut to the System Properties sheet from the System Control Panel item. Select Allow remote connections to this computer, and optionally enable Allow connections only from computers running Remote Destkop with Network Level Authentication (recommended).

Network Level Authentication (NLA) protects Windows Server against denial-of-service (DoS) attacks by requiring authentication to take place before any graphical session is established by the server. NLA also conserves server system resources.

Windows PowerShell

From a lower-level perspective, incoming RDP connections are enabled on a server through two Registry values and a Windows Firewall rule.
Open an elevated Windows PowerShell session and run the following commands. This first one creates the fDenyTSConnections value and sets it to 0 (off). This makes sense, because we don’t want to deny Terminal Services (TS) connections.

New-ItemProperty -Path ‘HKLM:SystemCurrentControlSetControlTerminal Server’ -Name ‘fDenyTSConnections’ -Value 0 -PropertyType dword -Force

The next command creates and enables the UserAuthentication (Network Layer Authentication) value; NLA is a good idea and you should consider enabling it by default on your servers.

New-ItemProperty -Path ‘HKLM:SystemCurrentControlSetControlTerminal ServerWinStationsRDP-Tcp’ -Name ‘UserAuthentication’ -Value 1 -PropertyType dword -Force

The next command enables the predefined «Remote Desktop» Windows Firewall rule. We can then invoke the Get-NetFirewallRule PowerShell cmdlet to verify as shown in Figure 3.
Enable-NetFirewallRule -DisplayGroup ‘Remote Desktop’

Group Policy

The chances are good that you want to standardize RDP behavior across all your infrastructure servers. Therefore, we turn to Group Policy to accomplish this goal.

Start by creating, linking and scoping a new Group Policy Object (GPO) that targets the servers that should share RDP server settings.

Next, navigate to the following Group Policy path and add a new Restricted Groups entry (shown in Figure 4):
Computer ConfigurationPoliciesWindows SettingsSecurity SettingsRestricted Groups

You can customize the membership in the servers’ built-in Remote Desktop Users group; members of this group can establish RDP sessions to the server. Note that the local Administrators group (and, by extension, the Domain Admins global group) is automatically granted this privilege in Active Directory.

The following three Group Policy settings govern:

  • Windows Firewall incoming RDP exceptions
  • User right to establish RDP sessions
  • Requiring NLA

Computer ConfigurationAdministrative TemplatesNetworkNetwork ConnectionsWindows FirewallDomain ProfileWindows Firewall: Allow Inbound Remote Desktop exceptions

Computer ConfigurationAdministrative TemplatesWindows ComponentsRemote Desktop ServicesRemote Desktop Session HostConnectionsAllow user to connect remotely by using Remote Desktop Services

Computer ConfigurationAdministrative TemplatesWindows ComponentsRemote Desktop ServicesRemote Desktop Session HostSecurityRequire user authentication for remote connections by using NLA

Creating the Client Connection

Windows Client and Windows Server both include the Microsoft RDP client, called Remote Desktop Connection. My favorite way to invoke this tool is to:

Press WINDOWS KEY+R

Type mstsc (which stands for «Microsoft Terminal Services Client»)

Press ENTER

I show you the Remote Desktop Connection user interface in Figure 5.

What’s cool about RDP clients is that they are available for just about every desktop or mobile operating system. Here is a representative list:

  • Android: Microsoft Remote Desktop
  • iOS: Microsoft Remote Desktop
  • Linux: rdesktop
  • macOS: Microsoft Remote Desktop
  • Windows Phone: Microsoft Remote Desktop

Note that Windows Server supports only two simultaneous RDP sessions at once. If you need more than that, then you’ll have to install the Remote Desktop Services (RDS) Session Host server role and purchase additional RDS connection licenses from Microsoft.

Final Thoughts

If you’ve configured RDP on previous Windows Server versions, then you’ll find that Windows Server 2016 behaves the exact same way. Keep in mind, however, that Microsoft’s ever-widening embrace of «assume breach» security posture and the hybrid cloud scenario and its accompanying «manage herds, not pets» philosophy means the emphasis is on command-line automation rather than on-off RDP GUI sessions.

  • 10 Best New Features in Windows Server 2016
  • Windows 10 for IT Pros: Tutorials, Tips and Tricks
  • Top 6 Windows 10 Apps for IT Pros

Get instant access to breaking news, in-depth reviews and helpful tips.

Remote Desktop Protocol (RDP) is a Microsoft-proprietary remote access protocol that is used by Windows systems administrators to manage Windows Server systems remotely. What sets RDP apart from, say, Windows PowerShell or Secure Shell (SSH) remoting is the presence of the full graphical desktop, as shown in Figure 1.

MORE: Best Remote Access Software and Solutions

By default, the RDP server component listens for incoming connections on TCP port 3389 by default, although this can be changed by the administrator for security reasons.

To be sure, Microsoft’s current push is for admins to reduce their reliance upon RDP and instead (a) deploy Windows Servers in Server Core or Nano mode; and (b) employ Windows PowerShell command-line remote administration instead of RDP.

Microsoft’s justification for this advice is two-fold:

  • A GUI layer consumes unnecessary system resources
  • A GUI layer broadens the attack surface of your servers

Regardless, many admins are accustomed to RDP-based remote administration, and seek to do so even in the newly released Windows Server 2016 operating system. Let’s learn how to enable RDP in Server 2016 (tl;dr: the process is identical to Windows Server 2012 R2).

Server Manager

Open the Server Manager console, navigate to the Local Server node, and click the Remote Desktop hyperlink as shown in Figure 2.

The Remote Desktop hyperlink is simply a shortcut to the System Properties sheet from the System Control Panel item. Select Allow remote connections to this computer, and optionally enable Allow connections only from computers running Remote Destkop with Network Level Authentication (recommended).

Network Level Authentication (NLA) protects Windows Server against denial-of-service (DoS) attacks by requiring authentication to take place before any graphical session is established by the server. NLA also conserves server system resources.

Windows PowerShell

From a lower-level perspective, incoming RDP connections are enabled on a server through two Registry values and a Windows Firewall rule.
Open an elevated Windows PowerShell session and run the following commands. This first one creates the fDenyTSConnections value and sets it to 0 (off). This makes sense, because we don’t want to deny Terminal Services (TS) connections.

New-ItemProperty -Path ‘HKLM:SystemCurrentControlSetControlTerminal Server’ -Name ‘fDenyTSConnections’ -Value 0 -PropertyType dword -Force

The next command creates and enables the UserAuthentication (Network Layer Authentication) value; NLA is a good idea and you should consider enabling it by default on your servers.

New-ItemProperty -Path ‘HKLM:SystemCurrentControlSetControlTerminal ServerWinStationsRDP-Tcp’ -Name ‘UserAuthentication’ -Value 1 -PropertyType dword -Force

The next command enables the predefined «Remote Desktop» Windows Firewall rule. We can then invoke the Get-NetFirewallRule PowerShell cmdlet to verify as shown in Figure 3.
Enable-NetFirewallRule -DisplayGroup ‘Remote Desktop’

Group Policy

The chances are good that you want to standardize RDP behavior across all your infrastructure servers. Therefore, we turn to Group Policy to accomplish this goal.

Start by creating, linking and scoping a new Group Policy Object (GPO) that targets the servers that should share RDP server settings.

Next, navigate to the following Group Policy path and add a new Restricted Groups entry (shown in Figure 4):
Computer ConfigurationPoliciesWindows SettingsSecurity SettingsRestricted Groups

You can customize the membership in the servers’ built-in Remote Desktop Users group; members of this group can establish RDP sessions to the server. Note that the local Administrators group (and, by extension, the Domain Admins global group) is automatically granted this privilege in Active Directory.

The following three Group Policy settings govern:

  • Windows Firewall incoming RDP exceptions
  • User right to establish RDP sessions
  • Requiring NLA

Computer ConfigurationAdministrative TemplatesNetworkNetwork ConnectionsWindows FirewallDomain ProfileWindows Firewall: Allow Inbound Remote Desktop exceptions

Computer ConfigurationAdministrative TemplatesWindows ComponentsRemote Desktop ServicesRemote Desktop Session HostConnectionsAllow user to connect remotely by using Remote Desktop Services

Computer ConfigurationAdministrative TemplatesWindows ComponentsRemote Desktop ServicesRemote Desktop Session HostSecurityRequire user authentication for remote connections by using NLA

Creating the Client Connection

Windows Client and Windows Server both include the Microsoft RDP client, called Remote Desktop Connection. My favorite way to invoke this tool is to:

Press WINDOWS KEY+R

Type mstsc (which stands for «Microsoft Terminal Services Client»)

Press ENTER

I show you the Remote Desktop Connection user interface in Figure 5.

What’s cool about RDP clients is that they are available for just about every desktop or mobile operating system. Here is a representative list:

  • Android: Microsoft Remote Desktop
  • iOS: Microsoft Remote Desktop
  • Linux: rdesktop
  • macOS: Microsoft Remote Desktop
  • Windows Phone: Microsoft Remote Desktop

Note that Windows Server supports only two simultaneous RDP sessions at once. If you need more than that, then you’ll have to install the Remote Desktop Services (RDS) Session Host server role and purchase additional RDS connection licenses from Microsoft.

Final Thoughts

If you’ve configured RDP on previous Windows Server versions, then you’ll find that Windows Server 2016 behaves the exact same way. Keep in mind, however, that Microsoft’s ever-widening embrace of «assume breach» security posture and the hybrid cloud scenario and its accompanying «manage herds, not pets» philosophy means the emphasis is on command-line automation rather than on-off RDP GUI sessions.

  • 10 Best New Features in Windows Server 2016
  • Windows 10 for IT Pros: Tutorials, Tips and Tricks
  • Top 6 Windows 10 Apps for IT Pros

Get instant access to breaking news, in-depth reviews and helpful tips.

Оглавление

  • Добавление ролей и компонентов
  • Активация лицензии удалённых рабочих столов
  • Изменение стандартного порта подключения
  • Возможные проблемы
  • Подключение было запрещено
  • CredSSP
  • Отсутствуют доступные серверы лицензирования удаленных рабочих столов

Добавление ролей и компонентов

Установка самой оси Microsoft Windows Server 2016 в рамках данной статьи рассматриваться не будет, только отдельно сама установка терминального сервера.
На будущем терминальном сервере открываем диспетчер сервера через Панель управления (Win + R Control) — АдминистрированиеДиспетчер серверов (Server Manager)
или через команду «Выполнить» (Win + R ServerManager). После чего переходим по вкладке Локальный сервер (Local Server)

Открываем мастер добавления ролей и компонентов, жмём далее, в типе установки отмечаем радиокнопкой пункт Установка ролей или компонентов (Role-based or feature-based installation),
выбираем сервер, жмём далее, чекбоксом отмечаем Службы удаленных рабочих столов. В службах ролей отмечаем для установки две службы: Лицензирование удаленных рабочих столов (Remote Desktop Licensing) и Узел сеансов удаленных рабочих столов (Remote Desktop Session Host),
жмём далее и потом установить. Дожидаемся конца установки и перезагружаем сервер, если это не было сделано автоматически по завершению установки.

Активация лицензии удалённых рабочих столов

СредстваRemote Desktop ServicesДиспетчер лицензирования удаленных рабочих столов (RD Licensing Manager).
Раскрываем древо, правой кнопкой по нашему серверу вызываем выпадающее меню и выбираем пункт активировать сервер.

В мастер активации сервера вначале заполняем сведения об организации, а после устанавливаем саму лицензию. При выборе программы лицензии указываем Другое соглашение,
и указываем ключи активации купленной лицензии 6565792 (или любой другой. Для тестового сервера нагуглите за 2 минуты:»номер соглашения windows server 2016«. Ключ 6565792 — также является результатом выдачи поисковика google).
Выбираем версию продукта Windows Server 2016и тип лицензии Клиентская лицензия служб удаленных рабочих столов (на пользователя). Готово!

Но Средство диагностики лицензирования удаленных рабочих столов сообщает нам, что сервер лицензирования не включён. Чтож, поправим это дело через политики. Вызываем
командное меню «Выполнить» Win + R gpedit.msc. Переходим: Конфигурация компьютера (Computer Configuration) — Административные шаблоны (Administrative Templates) — Компоненты Windows (Windows Components) — Службы удаленных рабочих столов (Remote Desktop Services) — Узел сеансов удаленных рабочих столов (Remote Desktop Session Host) — Лицензирование (Licensing).

Тут поправим Использовать указанные серверы лицензирования удаленных рабочих столов (Use the specified Remote Desktop license servers) и Задать режим лицензирования удаленных рабочих столов (Set the Remote licensing mode).

Обновляем сведения в оснастке Средство диагностики лицинзирования удаленных рабочих столов (Win + R lsdiag.msc). Теперь всё ок!

Изменение стандартного порта подключения

Стандартный порт для RDP подключения: 3389

Открываем реестр (Win + R regedit), переходим по ветке:

HKEY_LOCAL_MACHINESystemCurrentControlSetControlTerminal ServerWinStationsRDP-Tcp

Находим ключ PortNumber, меняем систему исчисления на Десятичную и задаем необходимый номер порта.
Так же это можно сделать через командную строу:

reg add "HKLMSystemCurrentControlSetControlTerminal ServerWinStationsRDP-Tcp" /v PortNumber /t REG_DWORD /d НОВЫЙ_НОМЕР_ПОРТА /f

А чтобы вы потом смогли подключиться по новому порту, то вам в фаервол нужно прописать правило

netsh advfirewall firewall add rule name="RDP PORT НОВЫЙ_НОМЕР_ПОРТА" dir=in action=allow protocol=TCP localport=НОВЫЙ_НОМЕР_ПОРТА

И перезапустить службу

net stop TermService && net start TermService

Возможные проблемы

Подключение было запрещено

Скорее всего вы при попытке подключиться увидите сообщение:»Подключение было запрещено, так как учетная запись пользователя не имеет прав для удаленного входа в систему«,
а всё из-за того, что 1 — терминальный сервер не настроен в домене на разрешение подключения к нему определённых пользователей; 2 — вы не добавили в группу Пользователи удаленного рабочего стола ни одного пользователя.

Возможно вам будет полезна статья о том как из Windows 10 сделать Терминальный сервер.

CredSSP

Ещё можете столкнуться с такой вот ошибкой: An authentication error has occurred. The function is not supported. This could be due to CredSSP encryption oracle remediation.

О ней я писал ранее в статье:»Ошибка RDP подключения: CredSSP encryption oracle remediation. Как исправить?».

А возникновение этой ошибки связано с тем, что на терминальном Windows сервере, на который идёт подключение, не установлены последние обновления безопасности (CredSSP обновления для CVE-2018-0886). После обновления система по умолчанию запрещает подключаться к удалённым серверам по RDP со старой версией протокола CredSSP.

Отсутствуют доступные серверы лицензирования удаленных рабочих столов

После настройки сервера всё шло хорошо, но только 120 дней. Потом случилось следущее:

Удаленный сеанс отключен, поскольку отсутствуют доступные серверы лицензирования удаленных рабочих столов.
Обратитесь к администратору сервера

А это означает что у вас установлен ключ льготного периода (grace period licensing), который необходимо удалить. Для этого вам нужно залогиниться на сервер локально.
Где удалять ключ льготного периода? В реестре под именем L$RTMTIMEBOMB. Идём по ветке реестра:

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlTerminal ServerRCMGracePeriod

Но не тут то было! У вас недостаточно прав, но и это нас не остановит. Жмём правой кнопкой мыши и меняем владельца на ветку реестра и даём полные права самому себе, после чего спокойно удаляем эту гадость).
Если не поможет, то советую переустановить роли и компоненты.

Remote management of Windows Server 2016 is enabled by default, but Remote Desktop, on the other hand, is disabled. So, you have to turn it on in order to access a Windows Server remotely.

Depending on the case, we can enable the Remote Desktop directly using the graphical user interface, PowerShell or by implementing the appropriate policies through Group Policy.

Note: In Windows Server 2016 Essentials, Remote Desktop is enabled by default.

Enable Remote Desktop using the GUI

Open Server Manager and click Local Server from the left pane. Here, click Disable in the Remote Desktop field.

Enable Remote Desktop in Windows Server 2016

In the window that appears, enable the Allow remote connections to this computer setting. At this point, you can choose whether to allow NLA connections by enabling the corresponding setting but also to select which additional users or groups to connect other than administrators.

Enable Remote Desktop in Windows Server 2016

Once you’ve enabled the above setting, you’ll see a message to enable the corresponding Windows Firewall rule that will allow Remote Desktop Connection from any source address.

That’s it! Once you upgrade to Server Manager, you will see that the Remote Desktop setting has changed to Enabled.

Enable Remote Desktop using PowerShell

To enable Remote Desktop through PowerShell, you will need to add two keys to the registry and a rule in the Windows Firewall. Commands should run in a PowerShell window with administrator privileges.

By running the following command, the Remote Desktop will be enabled, allowing connections via Terminal Services.

New-ItemProperty -Path 'HKLM:SystemCurrentControlSetControlTerminal Server' - Name "fDenyTSConnections" -Value 0 -PropertyType dword -Force

By running the following command, the predefined Windows Firewall rules will be activated for the Remote Desktop on all profiles.

Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

Finally, the following command enables Network Level Authentication (NLA) for Remote Desktop connections.

New-ItemProperty -Path 'HKLM:SystemCurrentControlSetControlTerminal ServerWinStationsRDP-Tcp' -Name "UserAuthentication" -Value 1 -PropertyType dword -Force

Enable Remote Desktop using Group Policy

To enable Remote Desktop Connection, follow the path below and set the Allow users to connect remotely using Remote Desktop Services to Enabled.

Computer Configuration Policies Administrative Templates Remote Desktop Services Remote Desktop Session Host Connections

To enable user authentication through Network Level Authentication (NLA), follow the path below and set the Require Network User Authentication policy to Enabled.

Computer Configuration Policies Administrative Templates Remote Desktop Services Remote Desktop Session Host Security

To enable the rules in the Windows Firewall, follow the path below and set the policy Windows Firewall: Allow inbound Remote Desktop exceptions to Enabled.

Computer Configuration Policies Administrative Templates Network Network Connections Windows Firewall Domain Profile

These were the three basic methods to enable Remote Desktop connections in Windows Server 2016. Of course, depending on your business security level, you may need to go ahead with further settings for who can access and from where.


Posted by
on April 27, 2016

By default in Windows Server 2016 remote desktop is disabled.

Here we cover how to turn on and enable remote desktop protocol (RDP).

Note: In Windows Server 2016 Essentials edition, remote desktop is already enabled by default so you will not need to manually do this.

Remote desktop can be enabled through the graphical user interface (GUI) with the following easy steps.

Allowing Remote Desktop

  1. Open Server Manager. By default Server Manager will open when you log in to the GUI, otherwise you can select it from the task bar.
  2. Within the Server Manager window, select Local Server from the left hand side. You may need to wait a little for it to detect the current state of your system. You should see that Remote Desktop is listed as Disabled as shown below.

    Enable Remote Desktop Server Manager Check Status

  3. Click on the Disabled text which will open the System Properties window in the Remote tab.
  4. From the System Properties window, select “Allow remote connections to this Computer” as shown below.

    Allow remote connections to this computer

    Tip: You can also open the System Properties window shown above by entering “SystemPropertiesRemote” into a Command Prompt or PowerShell terminal.

  5. Once you select “Allow remote connections to this computer” the below warning message will appear, advising that this will create the required firewall rules in Windows firewall to allow remote desktop traffic in from any source address, select OK to proceed.

    Enable Remote Desktop Add Firewall Rule

  6. At this point you can optionally click the “Select Users…” button to define specific users or groups that have permission to connect via remote desktop. Select the OK button to close out of the System Properties window and enable remote desktop.
  7. Back in Server Manager, Remote Desktop may still show as Disabled until you refresh the view. After clicking the refresh button as highlighted below, the status should update to Enabled.

    Enable Remote Desktop Server Manager Check Status

That’s it, remote desktop should now be ready to use!

Summary

By default Windows Server 2016 sets external remote desktop access to disabled as a security measure, we can easily optionally enable it from within the server console to everyone or a specific set of users or groups.

Понравилась статья? Поделить с друзьями:
  • Настройка ftp сервера на windows server 2019 iis
  • Настройка firewall windows server 2012 r2
  • Настройка far manager в windows 10
  • Настройка fallout 3 для windows 10
  • Настройка failover dhcp windows server 2012