Windows remote desktop logging

Tracking and Analyzing Remote Desktop Activity Logs in Windows

In this article we’ll consider the features of auditing and analyzing RDP connection logs in Windows. As a rule, the described methods may be useful when investigating RDP-related activity on RDS (terminal) Windows servers in forensics tasks, when a system administrator must provide the information about what users logged on to the RDS server, when a specific RDP user authenticated and ended up the session, which device (a name or IP address) an user connected from. I think this information will be useful both for the administrators of corporate RDS farms and for owners of a separate RDP servers what are published in the Internet (Windows VPS are still quite popular).

You can check the RDP connection logs using Windows Event Viewer ( eventvwr.msc ). Windows logs contain a lot of data, and it is quite difficult to find the event you need. When a user remotely connects to the remote desktop of RDS (RDP), a whole number of events appears in the Windows Event Viewer. There are several different logs where you can find the information about Remote Desktop connections. We’ll look at the logs and events on the main stages of an RDP connection that may be of interest to the administrator:

  1. Network Connection;
  2. Authentication;
  3. Logon;
  4. Session Disconnect/Reconnect;
  5. Logoff.

Network Connection is the establishment of a network connection to a server from a user RDP client. It is the event with the EventID 1149 ( Remote Desktop Services: User authentication succeeded ). If this event is found, it doesn’t mean that user authentication has been successful. This log is located in “Applications and Services Logs -> Microsoft -> Windows -> Terminal-Services-RemoteConnectionManager > Operational”. Enable the log filter for this event (right-click the log -> Filter Current Log -> EventId 1149).

Then you will get an event list with the history of all RDP connections to this server. As you can see, the logs provide a username, a domain (in this case the Network Level Authentication is used; if NLA is disabled, the event text looks differently) and the IP address of the computer, from which the RDP connection has been initiated.

Authentication shows whether an RDP user has been successfully authenticated on the server or not. The log is located in “Windows -> Security”. So you may be interested in the events with the EventID 4624 ( An account was successfully logged on ) or 4625 ( An account failed to log on ). Please, pay attention to the LogonType value in the event description. If the Remote Desktop service has been use to create new session during log on, LogonType = 10. If the LogonType = 7, it means that a user has reconnected to the existing RDP session.

At the same time, you can find a user name in the event description in the Account Name field, a computer name – in Workstation Name, and an IP address – in Source Network Address.

You can get the list of events related to successful RDP authentication (EventID 4624) using this PowerShell command:

Get-EventLog security -after (Get-date -hour 0 -minute 0 -second 0) | ? <$_.eventid -eq 4624 -and $_.Message -match 'logon type:\s+(10)\s'>| Out-GridView

Logon refers to an RDP logon to the system, an event that appears after a user has been successfully authenticated. It is an event with the EventID 21 ( Remote Desktop Services: Session logon succeeded ). This events are located in the “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”. As you can see, here you can find the ID of a user RDP session — Session ID.

The event with the EventID – 21 ( Remote Desktop Services: Shell start notification received ) means that the Explorer shell has been successfully started (the desktop appears in the user’s RDP session).

Session Disconnect/Reconnect – session disconnection / reconnection events have different IDs depending on what caused user disconnection (disconnection to inactivity, Disconnect option has been selected by the user in the session, RDP session ended by another user or an administrator, etc.). You can find these events in the logs located in “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”. Let’s consider the most interesting RDP events:

Читайте также:  Windows booting from wrong drive

The event with the EventID 4778 in Windows -> Security log (A session was reconnected to a Window Station). A user has reconnected to an RDP session (a user is assigned a new LogonID).

The event with the EventID 4799 in “Windows -> Security” log ( A session was disconnected from a Window Station ). A user has been disconnected from an RDP session.

Logoff refers to the user logoff from the system. It is logged as the event with the EventID 23 ( Remote Desktop Services: Session logoff succeeded ) in “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”.

At the same time the event with the EventID 4634 ( An account was logged off ) appears in the Security log.

The event with the EventID 9009 ( The Desktop Window Manager has exited with code ) in the System log means that a user has initiated logoff from the RDP session with both the window and the graphic shell of the user have been terminated.

Here is a short PowerShell script that lists the history of all RDP connections for the current day from the terminal RDS server logs. The resulting table shows the connection time, the client’s IP address and the remote user name (if necessary, you can include other LogonTypes to the report).

Sometimes it can be more convenient to view and investigate RDP logs in the Excel table, so you can export any Windows events into a text file and import it in Excel. You can export the log from the Event Viewer GUI (only if the event logs are not cleared), from the command prompt:

WEVTUtil query-events Security > c:\ps\rdp_security_log.txt

get-winevent -logname «Microsoft-Windows-TerminalServices-LocalSessionManager/Operational» | Export-Csv c:\ps\rdp_connection_log.txt -Encoding UTF8

You can display the list of current remote sessions on your RDS server using this command:

The command returns the session ID (ID), the name of user (USERNAME) and the session state (Active/Disconnect). It is convenient to use this command when you need to get the ID of the user RDP session in case shadow connection is used.

You can display the list of the running processes in the specific RDP session (the session ID is specified):

Logs on an RDP client side are not quite informative, but you can check the history of RDP connections in the user’s registry.

Allow log on through Remote Desktop Services

Applies to

Describes the best practices, location, values, policy management, and security considerations for the Allow log on through Remote Desktop Services security policy setting.

Reference

This policy setting determines which users or groups can access the logon screen of a remote device through a Remote Desktop Services connection. It is possible for a user to establish a Remote Desktop Services connection to a particular server but not be able to log on to the console of that same server.

Possible values

  • User-defined list of accounts
  • Not Defined

Best practices

  • To control who can open a Remote Desktop Services connection and log on to the device, add users to or remove users from the Remote Desktop Users group.

Location

Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment

Default values

By default, members of the Administrators group have this right on domain controllers, workstations, and servers. The Remote Desktops Users group also has this right on workstations and servers. The following table lists the actual and effective default policy values. Default values are also listed on the policy’s property page.

Server type or GPO Default value
Default Domain Policy Not Defined
Default Domain Controller Policy Not Defined
Domain Controller Local Security Policy Administrators
Stand-Alone Server Default Settings Administrators
Remote Desktop Users
Domain Controller Effective Default Settings Administrators
Member Server Effective Default Settings Administrators
Remote Desktop Users
Client Computer Effective Default Settings Administrators
Remote Desktop Users

Policy management

This section describes different features and tools available to help you manage this policy.

Group Policy

To use Remote Desktop Services to successfully log on to a remote device, the user or group must be a member of the Remote Desktop Users or Administrators group and be granted the Allow log on through Remote Desktop Services right. It is possible for a user to establish an Remote Desktop Services session to a particular server, but not be able to log on to the console of that same server.

To exclude users or groups, you can assign the Deny log on through Remote Desktop Services user right to those users or groups. However, be careful when you use this method because you could create conflicts for legitimate users or groups that have been allowed access through the Allow log on through Remote Desktop Services user right.

A restart of the device is not required for this policy setting to be effective.

Any change to the user rights assignment for an account becomes effective the next time the owner of the account logs on.

Group Policy settings are applied through GPOs in the following order, which will overwrite settings on the local computer at the next Group Policy update:

  1. Local policy settings
  2. Site policy settings
  3. Domain policy settings
  4. OU policy settings

Security considerations

This section describes how an attacker might exploit a feature or its configuration, how to implement the countermeasure, and the possible negative consequences of countermeasure implementation.

Vulnerability

Any account with the Allow log on through Remote Desktop Services user right can log on to the remote console of the device. If you do not restrict this user right to legitimate users who must log on to the console of the computer, unauthorized users could download and run malicious software to elevate their privileges.

Countermeasure

For domain controllers, assign the Allow log on through Remote Desktop Services user right only to the Administrators group. For other server roles and devices, add the Remote Desktop Users group. For servers that have the Remote Desktop (RD) Session Host role service enabled and do not run in Application Server mode, ensure that only authorized IT personnel who must manage the computers remotely belong to these groups.

Caution:В В For RD Session Host servers that run in Application Server mode, ensure that only users who require access to the server have accounts that belong to the Remote Desktop Users group because this built-in group has this logon right by default.

Alternatively, you can assign the Deny log on through Remote Desktop Services user right to groups such as Account Operators, Server Operators, and Guests. However, be careful when you use this method because you could block access to legitimate administrators who also belong to a group that has the Deny log on through Remote Desktop Services user right.

Potential impact

Removal of the Allow log on through Remote Desktop Services user right from other groups (or membership changes in these default groups) could limit the abilities of users who perform specific administrative roles in your environment. You should confirm that delegated activities are not adversely affected.

Просмотр и анализ логов RDP подключений в Windows

В этой статье мы рассмотрим, особенности аудита / анализа логов RDP подключений в Windows. Как правило, описанные методы могут пригодиться при расследовании различных инцидентов на терминальных / RDS серверах Windows, когда от системного администратора требуется предоставить информацию: какие пользователи входили на RDS сервер, когда авторизовался и завершил сеанс конкретный пользователь, откуда / с какого устройства (имя или IP адрес) подключался RDP-пользователь. Я думаю, эта информация будет полезна как для администраторов корпоративных RDS ферм, так и владельцам RDP серверов в интернете (Windows VPS как оказалось довольно популярны).

Как и другие события, логи RDP подключения в Windows хранятся в журналах событий. Откройте консоль журнала событий (Event Viewer). Есть несколько различных журналов, в которых можно найти информацию, касающуюся RDP подключения.

В журналах Windows содержится большое количество информации, но быстро найти нужное событие бывает довольно сложно. Когда пользователь удаленно подключается к RDS серверу или удаленному столу (RDP) в журналах Windows генерируется много событий. Мы рассмотрим журналы и события на основных этапах RDP подключения, которые могут быть интересны администратору:

  1. Network Connection
  2. Authentication
  3. Logon
  4. Session Disconnect/Reconnect
  5. Logoff

Network Connection: – установление сетевого подключение к серверу от RDP клиента пользователя. Событие с EventID – 1149 (Remote Desktop Services: User authentication succeeded). Наличие этого события не свидетельствует об успешной аутентификации пользователя. Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> Terminal-Services-RemoteConnectionManager -> Operational. Включите фильтр по данному событию (ПКМ по журналу-> Filter Current Log -> EventId 1149).

В результате у вас получится список с историей всех сетевых RDP подключений к данному серверу. Как вы видите, в логах указывается имя пользователя, домен (используется NLA аутентификация, при отключенном NLA текст события выглядит иначе) и IP адрес компьютера, с которого осуществляется RDP подключение.

Authentication: – успешная или неуспешная аутентификация пользователя на сервере. Журнал Windows -> Security. Соответственно нас могут интересовать события с EventID – 4624 (успешная аутентификация — An account was successfully logged on) или 4625 (ошибка аутентификации — An account failed to log on). Обратите внимание на значение LogonType в событии. При входе через терминальную службу RDP — LogonType = 10 или 3. Если LogonType = 7, значит выполнено переподключение к уже имеющейся RDP сессии.

При этом имя пользователя содержится в описании события в поле Account Name, имя компьютера в Workstation Name, а имя пользователя в Source Network Address.

Вы можете получить список событий успешных авторизаций по RDP (событие 4624) с помощью такой команды PowerShell.

Get-EventLog security -after (Get-date -hour 0 -minute 0 -second 0) | ? <$_.eventid -eq 4624 -and $_.Message -match 'logon type:\s+(10)\s'>| Out-GridView

Logon: – RDP вход в систему, событие появляющееся после успешной аутентификации пользователя. Событие с EventID – 21 (Remote Desktop Services: Session logon succeeded). Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Как вы видите здесь можно узнать идентификатор RDP сессии для пользователя — Session ID.

Событие с EventID – 21 (Remote Desktop Services: Shell start notification received) означает успешный запуск оболочки Explorer (появление окна рабочего стола в RDP сессии).

Session Disconnect/Reconnect – события отключения / переподключения к сессии имеют разные коды в зависимости от того, что вызвало отключение пользователя (отключение по неактивности, выбор пункта Disconnect в сессии, завершение RDP сессии другим пользователем или администратором и т.д.). Эти события находятся в разделе журналов Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Рассмотрим RDP события, которые могут быть интересными:

Событие с EventID – 4778 в журнале Windows -> Security (A session was reconnected to a Window Station). Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID).

Событие с EventID 4799 в журнале Windows -> Security (A session was disconnected from a Window Station). Отключение от RDP сеанса.

Logoff: – выход пользователя из системы. При этом в журнале Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational фиксируется событие с EventID 23 (Remote Desktop Services: Session logoff succeeded).

При этом в журнале Security нужно смотреть событие EventID 4634 (An account was logged off).

Событие Event 9009 (The Desktop Window Manager has exited with code ( ) в журнале System говорит о том, что пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен.

Ниже представлен небольшой PowerShell, который выгружает из журналов терминального RDS сервера историю всех RDP подключений за текущий день. В полученной таблице указано время подключения, IP адрес клиента и имя RDP пользователя (при необходимости вы можете включить в отчет другие типы входов).

Иногда бывает удобно с логами в таблице Excel, в этом случае вы можете выгрузить любой журнал Windows в текстовый файл и импортировать в Excel. Экспорт журнала можно выполнить из консоли Event Viewer (конечно, при условии что логи не очищены) или через командную строку:

WEVTUtil query-events Security > c:\ps\security_log.txt

get-winevent -logname «Microsoft-Windows-TerminalServices-LocalSessionManager/Operational» | Export-Csv c:\ps\rdp-log.txt -Encoding UTF8

Список текущих RDP сессий на сервере можно вывести командой:

Команда возвращает как идентификатор сессии (ID), имя пользователя (USERNAME)и состояние (Active/Disconnect). Эту команду удобна использовать, когда нужно определить ID RDP сессии пользователя при теневом подключении.

Список запущенных процессов в конкретной RDP сессии (указывается ID сессии):

На RDP-клиенте логи не такие информационные, основное чем часто пользуются информация об истории RDP подключений в реестре.

Читайте также:  Windows не видит рабочую флешку
Оцените статью