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:
- Network Connection;
- Authentication;
- Logon;
- Session Disconnect/Reconnect;
- 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:
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.
Просмотр и анализ логов RDP подключений в Windows
В этой статье мы рассмотрим, особенности аудита / анализа логов RDP подключений в Windows. Как правило, описанные методы могут пригодиться при расследовании различных инцидентов на терминальных / RDS серверах Windows, когда от системного администратора требуется предоставить информацию: какие пользователи входили на RDS сервер, когда авторизовался и завершил сеанс конкретный пользователь, откуда / с какого устройства (имя или IP адрес) подключался RDP-пользователь. Я думаю, эта информация будет полезна как для администраторов корпоративных RDS ферм, так и владельцам RDP серверов в интернете (Windows VPS как оказалось довольно популярны).
Как и другие события, логи RDP подключения в Windows хранятся в журналах событий. Откройте консоль журнала событий (Event Viewer). Есть несколько различных журналов, в которых можно найти информацию, касающуюся RDP подключения.
В журналах Windows содержится большое количество информации, но быстро найти нужное событие бывает довольно сложно. Когда пользователь удаленно подключается к RDS серверу или удаленному столу (RDP) в журналах Windows генерируется много событий. Мы рассмотрим журналы и события на основных этапах RDP подключения, которые могут быть интересны администратору:
- Network Connection
- Authentication
- Logon
- Session Disconnect/Reconnect
- 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 подключений в реестре.