Логи rdp подключений windows server 2012

В этой статье мы рассмотрим, как получить и проанализировать логи RDP подключений в Windows. Логи RDP подключений позволяют администраторам терминальных RDS

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

Описанные методики получения и исследования RDP логов применима как к Windows Server 2022/2019/2016/2012R2, так и для десктопных версий Windows 11, 10, 8.1 c.

Содержание:

  • События RDP подключений в журналах Windows (Event Viewer)
  • Получаем логи RDP подключений в Windows с помощью PowerShell
  • Логи RDP подключений на клиентах Windows

События RDP подключений в журналах Windows (Event Viewer)

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

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

1149 Terminal-Services-RemoteConnectionManager

С помощью PowerShell можно вывести список всех попыток RDP подключений:

$RDPAuths = Get-WinEvent -LogName 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational' -FilterXPath '<QueryList><Query Id="0"><Select>*[System[EventID=1149]]</Select></Query></QueryList>'
[xml[]]$xml=$RDPAuths|Foreach{$_.ToXml()}
$EventData = Foreach ($event in $xml.Event)
{ New-Object PSObject -Property @{
TimeCreated = (Get-Date ($event.System.TimeCreated.SystemTime) -Format 'yyyy-MM-dd hh:mm:ss K')
User = $event.UserData.EventXML.Param1
Domain = $event.UserData.EventXML.Param2
Client = $event.UserData.EventXML.Param3
}
} $EventData | FT

вывести журнал подключений к RDP/RDS серверу с помощью powershell

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

Remote Desktop Services: User authentication succeeded

Authentication: – успешная или неудачная аутентификация пользователя на сервере. Журнал Windows -> Security. Здесь нас могут интересовать события с EventID – 4624 (успешная аутентификация — An account was successfully logged on) или 4625 (ошибка аутентификации — An account failed to log on). Обратите внимание на значение LogonType в событии.

  • LogonType = 10 или 3 — при входе через терминальную службу RDP —.
  • LogonType = 7, значит выполнено переподключение к уже существующему RDP сеансу.
  • LogonType = 5 – событие RDP подключения к консоли сервера (в режиме mstsc.exe /admin)

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

rdp событие аутентфикации An account was successfully logged on

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

Обратите внимание на значение поля LogonID – это уникальный идентификатор сессии пользователя, с помощью которого можно отслеживать дальнейшую активность данного пользователя. Но при отключении от RDP сессии (disconnect) и повторного переподключения к той же сессии, пользователю будет выдан новый TargetLogonID (хотя RDP сессия осталась той же самой).

Вы можете получить список событий успешных авторизаций по 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

получиь журнал RDP входов с помощью PowerShell

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

Remote Desktop Services: Session logon succeeded

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

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

  • EventID – 24 (Remote Desktop Services: Session has been disconnected) – пользователь отключился от RDP сессии.
  • EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – пользователь переподключился к своей имеющейся RDP сессии на сервере.
  • EventID – 39 (Session <A> has been disconnected by session <B>) – пользователь сам отключился от своей RDP сессии, выбрав соответствующий пункт меню (а не просто закрыл окно RDP клиента). Если идентификаторы сессий разные, значит пользователя отключил другой пользователь (или администратор).
  • EventID – 40 (Session <A> has been disconnected, reason code <B>). Здесь нужно смотреть на код причины отключения в событии. Например:
    • reason code 0 (No additional information is available) – обычно говорит о том, что пользователь просто закрыл окно RDP клиента.
    • reason code 5 (The client’s connection was replaced by another connection) – пользователь переподключился к своей старой сессии.
    • reason code 11 (User activity has initiated the disconnect) – пользователь сам нажал на кнопку Disconnect в меню.

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

Событие с EventID 4779 в журнале 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).

Remote Desktop Services: Session logoff succeeded

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

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

EventID 4647 — User-initiated logoff

Получаем логи RDP подключений в Windows с помощью PowerShell

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

Get-EventLog -LogName Security -after (Get-date -hour 0 -minute 0 -second 0)| ?{(4624,4778) -contains $_.EventID -and $_.Message -match 'logon type:s+(10)s'}| %{
(new-object -Type PSObject -Property @{
TimeGenerated = $_.TimeGenerated
ClientIP = $_.Message -replace '(?smi).*Source Network Address:s+([^s]+)s+.*','$1'
UserName = $_.Message -replace '(?smi).*ssAccount Name:s+([^s]+)s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*ssAccount Domain:s+([^s]+)s+.*','$1'
LogonType = $_.Message -replace '(?smi).*Logon Type:s+([^s]+)s+.*','$1'
})
} | sort TimeGenerated -Descending | Select TimeGenerated, ClientIP `
, @{N='Username';E={'{0}{1}' -f $_.UserDomain,$_.UserName}} `
, @{N='LogType';E={
switch ($_.LogonType) {
2 {'Interactive - local logon'}
3 {'Network conection to shared folder)'}
4 {'Batch'}
5 {'Service'}
7 {'Unlock (after screensaver)'}
8 {'NetworkCleartext'}
9 {'NewCredentials (local impersonation process under existing connection)'}
10 {'RDP'}
11 {'CachedInteractive'}
default {"LogType Not Recognised: $($_.LogonType)"}
}
}}

логи RDP подключений к RDS серверу с IP адресами и учетными записями

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

WEVTUtil query-events Security > c:pssecurity_log.txt

Или с помощью PowerShell:

get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:psrdp-log.csv  -Encoding UTF8

Если ваши пользователи подключаются к RDS серверам через шлюз удаленных рабочих столов Remote Desktop Gateway, вы можете обрабатывать логи подключений пользователей по журналу Microsoft-Windows-TerminalServices-Gateway по EventID 302. Например, следующий PowerShell скрипт выведет полную историю подключений через RD Gateway указанного пользователя:

$rdpusername="kbuldogov"
$properties = @(
@{n='User';e={$_.Properties[0].Value}},
@{n='Source IP Adress';e={$_.Properties[1].Value}},
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='Target RDP host';e={$_.Properties[3].Value}}
)
(Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-Gateway/Operational';ID='302'} | Select-Object $properties) -match $rdpusername

powershell поиск в логах удаленных RDP подключений на remote desktop gateway в windows server 2019

Другие события, связанные с подключениями пользователей на RD Gateway в журнале Microsoft-Windows-TerminalServices-Gateway:

  • 300
    The user %1, on client computer %2, met resource authorization policy requirements and was therefore authorized to connect to resource %4
  • 302
    The user %1, on client computer %2, connected to resource %4
  • 303
    The user %1, on client computer %2, disconnected from the following network resource: %4. Before the user disconnected, the client transferred %6 bytes and received %5 bytes. The client session duration was %7 seconds.

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

qwinsta

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

Qwinsta

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

qprocess /id:157

qprocess

Логи RDP подключений на клиентах Windows

Также вы можете изучать логи исходящих подключений на стороне RDP клиента. Они доступны в журнале событий Application and Services Logs -> Microsoft -> Windows -> TerminalServices-ClientActiveXCore -> Microsoft-Windows-TerminalServices-RDPClient -> Operation.

Например, событие с Event ID 1102 появляется, когда компьютер устанавливает подключение с удаленным RDS хостом Windows Server или компьютером с Windows 10/11 с включенной службой RDP (десктопные версии Windows также поддерживают несколько одновременных rdp подключений).

The client has initiated a multi-transport connection to the server 192.168.31.102.

событие с ID 1102 в журнале Microsoft-Windows-TerminalServices-RDPClient событие подключения к RDP серверу на клиенте

Следующий RDP скрипт выведет историю RDP подключений на указанном компьютере (для получения событий Event Log используется командлет Get-WinEvent):

$properties = @(
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='LocalUser';e={$_.UserID}}
@{n='Target RDP host';e={$_.Properties[1].Value}}
)
Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-RDPClient/Operational';ID='1102'} | Select-Object $properties

powershell вывести история RDP подключений на клиентском компьютере

Скрипт возвращает SID пользователей, которые инициировали RDP подключения на этом компьютере и DNS имена/IP адреса серверов, к которым подключались пользователи. Вы можете преобразовать SID в имена пользователей.

Также история RDP подключений пользователя хранится в реестре.

In this article, we’ll describe how to get and audit the RDP connection logs in Windows. The RDP connection logs allow RDS terminal servers administrators to get information about which users logged on to the server when a specific RDP user logged on and ended up the session, and from which device (DNS name or IP address) the user logged on.

Contents:

  • RDP Connection Events in Windows Event Viewer
  • Getting Remote Desktop Login History with PowerShell
  • Outgoing RDP Connection Logs in Windows

The article is applicable when analyzing RDP logs for both Windows Server 2022/2019/2016/2012R2 and to desktop editions (Windows 11, 10, and 8.1).

RDP Connection Events in Windows Event Viewer

When a user connects to a Remote Desktop-enabled or RDS host, information about these events is stored in the Event Viewer logs (eventvwr.msc). Consider the main stages of RDP connection and related events in the Event Viewer, which may be of interest to the administrator

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

Network Connection – establishing a network connection to a server from the user’s 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).

windows event log Terminal-Services-RemoteConnectionManager filtering

You can list all RDP connection attempts with PowerShell:

$RDPAuths = Get-WinEvent -LogName 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational' -FilterXPath '<QueryList><Query Id="0"><Select>*[System[EventID=1149]]</Select></Query></QueryList>'
[xml[]]$xml=$RDPAuths|Foreach{$_.ToXml()}
$EventData = Foreach ($event in $xml.Event)
{ New-Object PSObject -Property @{
TimeCreated = (Get-Date ($event.System.TimeCreated.SystemTime) -Format 'yyyy-MM-dd hh:mm:ss K')
User = $event.UserData.EventXML.Param1
Domain = $event.UserData.EventXML.Param2
Client = $event.UserData.EventXML.Param3
}
} $EventData | FT

powershell script: get rdp conneciton events

Then you will get an event list with the history of all RDP connections to this server. The logs provide a username, a domain (in this case the Network Level Authentication is used; if NLA is disabled, the event description looks differently), and the IP address of the user’s computer.

EventID 1149 - Remote Desktop Services: User authentication succeeded

Authentication shows whether an RDP user has been successfully authenticated on the server or not. The log is located under 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.

  • LogonType = 10 or 3 — if the Remote Desktop service has been used to create a new session during log on;
  • LogonType = 7, means that a user has reconnected to the existing RDP session;
  • LogonType = 5 – RDP connection to the server console (in the mstsc.exe /admin mode).

security log: rdp logon event with the username and ip adress of the remote client

In this case, the user name is contained in the event description in the Account Name field, the computer name in the Workstation Name, and the user IP in the Source Network Address.

Please, note the value of the LogonID field. This is a unique user RDP session identifier that helps track the user’s further activity. However, if an RDP session is disconnected and a user reconnects to it, the user will be assigned a new LogonID (although the RDP session remains the same).

You can get a list of successful RDP authentication events (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

list sucess rdp auth event with an EventID 4624

Logon refers to an RDP login to Windows. EventID 21 – this event appears after a user has been successfully authenticated (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.

EventID 21 - Remote Desktop Services: Session logon succeeded

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

Session Disconnect/Reconnect – session disconnection and reconnection events have different IDs depending on what caused the user disconnection (disconnection due to inactivity set in timeouts for RDP sessions, 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 Event Viewer under “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”. Let’s consider the RDP Event IDs that might be useful:

  • EventID – 24 (Remote Desktop Services: Session has been disconnected) –a user has disconnected from the RDP session;
  • EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – a user has reconnected to the existing RDP session on the server;
  • EventID – 39 (Session <A> has been disconnected by session <B>) – a user has disconnected from the RDP session by selecting the corresponding menu option (instead of just closing the RDP client window). If the session IDs are different, a user has been disconnected by another user (or administrator);
  • EventID – 40 (Session <A> has been disconnected, reason code <B>). Here you must check the disconnection reason code in the event description. For example:
    • reason code 0 (No additional information is available) means that a user has just closed the RDP client window;
    • reason code 5 (The client’s connection was replaced by another connection) means that a user has reconnected to the previous RDP session;
    • reason code 11 (User activity has initiated the disconnect) a user has clicked the Disconnect button in the start menu.

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

EventID 4779 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 end of a user session. It is logged as the event with the EventID 23 (Remote Desktop Services: Session logoff succeeded) under “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”.

EventID 23 - Remote Desktop Services: Session logoff succeeded

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

The EventID 9009  (The Desktop Window Manager has exited with code <X>) 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.

EventID 4647 — User-initiated logoff

Getting Remote Desktop Login History with PowerShell

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

Get-EventLog -LogName Security -after (Get-date -hour 0 -minute 0 -second 0)| ?{(4624,4778) -contains $_.EventID -and $_.Message -match 'logon type:s+(10)s'}| %{
(new-object -Type PSObject -Property @{
TimeGenerated = $_.TimeGenerated
ClientIP = $_.Message -replace '(?smi).*Source Network Address:s+([^s]+)s+.*','$1'
UserName = $_.Message -replace '(?smi).*ssAccount Name:s+([^s]+)s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*ssAccount Domain:s+([^s]+)s+.*','$1'
LogonType = $_.Message -replace '(?smi).*Logon Type:s+([^s]+)s+.*','$1'
})
} | sort TimeGenerated -Descending | Select TimeGenerated, ClientIP `
, @{N='Username';E={'{0}{1}' -f $_.UserDomain,$_.UserName}} `
, @{N='LogType';E={
switch ($_.LogonType) {
2 {'Interactive - local logon'}
3 {'Network connection to shared folder)'}
4 {'Batch'}
5 {'Service'}
7 {'Unlock (after screensaver)'}
8 {'NetworkCleartext'}
9 {'NewCredentials (local impersonation process under existing connection)'}
10 {'RDP'}
11 {'CachedInteractive'}
default {"LogType Not Recognised: $($_.LogonType)"}
}
}}

powershell: list todays rdp logons with an ip and username

This method allows you to collect and parse RDP connection logs on a standalone RDSH server. If you have multiple servers in the RDS farm, you can query each of them with this script, or get logs from a management server with the Remote Desktop Connection Broker role.

You can export RDP connection logs from the Event Viewer to a CSV file (for further analysis in an Excel spreadsheet). You can export the log from the Event Viewer GUI (assuming Event Viewer logs are not cleared) or via the command prompt:

WEVTUtil query-events Security > c:psrdp_security_log.txt

Or with PowerShell:

get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:psrdp_connection_log.txt  -Encoding UTF8

If your users connect to corporate RDS hosts through the Remote Desktop Gateway, you can check the user connection logs in the Microsoft-Windows-TerminalServices-Gateway log by the EventID 302. For example, the following PowerShell script will display the specified user’s connection history through RD Gateway:

$rdpusername="b.smith"
$properties = @(
@{n='User';e={$_.Properties[0].Value}},
@{n='Source IP Adress';e={$_.Properties[1].Value}},
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='Target RDP host';e={$_.Properties[3].Value}}
)
(Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-Gateway/Operational';ID='302'} | Select-Object $properties) -match $rdpusername

rd gateway user connection logs

You can check the following RD Gateway user connection events in the Microsoft-Windows-TerminalServices-Gateway event log:

  • 300 — The user NAME, on client computer DEVICE, met resource authorization policy requirements and was therefore authorized to connect to resource RDPHOST;
  • 302 — The user NAME, on client computer DEVICE, connected to resource RDPHOST;
  • 303 — The user NAME, on client computer DEVICE, disconnected from the following network resource: RDPHOST. Before the user disconnected, the client transferred X bytes and received X bytes. The client session duration was X seconds.

You can display the list of current remote sessions on your RDS host with the command:

qwinsta
The command returns the session ID, the USERNAME, and the session state (Active/Disconnect). This command is useful when you need to get the user’s RDP session ID when using shadow Remote Desktop connections.

Qwinsta - list RDP sessions and usernames

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

qprocess /id:5

qprocess - get process list for an RDP session

Outgoing RDP Connection Logs in Windows

You can also view outgoing RDP connection logs on the client side. They are available in the following event log: Application and Services Logs -> Microsoft -> Windows -> TerminalServices-ClientActiveXCore -> Microsoft-Windows-TerminalServices-RDPClient -> Operational.

For example, EventID 1102 occurs when a user connects to a remote Windows Server RDS host or a Windows 10/11 computer with RDP enabled (desktop Windows editions also support multiple simultaneous RDP connections).

The client has initiated a multi-transport connection to the server 192.168.13.201.

Microsoft-Windows-TerminalServices-RDPClient connection event in Windows

The following RDP script will display the history of RDP client connections on the current computer:

$properties = @(
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='LocalUser';e={$_.UserID}}
@{n='Target RDP host';e={$_.Properties[1].Value}}
)
Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-RDPClient/Operational';ID='1102'} | Select-Object $properties

rdp client connection events

The script returns the SIDs of the users who initiated RDP connections on this computer, as well as the DNS names/IP addresses of the Remote Desktop hosts that the users connected to. You can convert SIDs to usernames as follows.

  • Remove From My Forums
  • Question

  • Our production servers use the same credentials for RDP access. Our support team which access those servers, uses those same RDP credentials to access those servers, but of course, each one of the support team members has it’s own desktop and private credentials.

    Is there a log in the server side which tracks all the RDP connections and maybe who is the client accessing it?

    Thank ahead.

    • Edited by

      Wednesday, October 23, 2013 8:58 AM

Answers

  • Hi,

    Having multiple users use the same credentials is not recommended for security and usability reasons.  In very rare, specialized cases it can make sense (for example, auto-logon kiosk for anonymous users or for special apps that will authenticate).

    If you want to continue with your current configuration one thing I can suggest is to have a script run at log on that logs the CLIENTNAME environment variable to a file and/or the event log.  For example, something like this:

    echo «%username%»,»%clientname%»,»%date%»,»%time%»>>c:logslogon.csv

    -TP

    • Marked as answer by
      Jeremy_Wu
      Wednesday, November 6, 2013 11:49 PM

Investigating lateral movement activities involving remote desktop protocol (RDP) is a common aspect when responding to an incident where nefarious activities have occurred within a network. Perhaps the quickest and easiest way to do that is to check the RDP connection security event logs on machines known to have been compromised for events with ID 4624 or 4625 and with a type 10 logon. However, that is not at all always a surefire way to detect if such activity has occurred.

It is becoming more and more common for bad actors to manipulate or clear the security event logs on compromised machines, and sometimes RDP sessions don’t even register as just a type 10 logon, depending on the circumstance. RDP activities, like most activities, will leave events in several different logs as action is taken and various processes are involved.

Log Events and Examples

As digital forensic investigators, we need to find the evidence we’re interested in and ensure we are not overlooking information that could also be available in the event logs, even after standard security log wipes.

Let’s consider the following logs and events:

SOURCE PC:
Security 4648
TerminalServices-RDPClient/Operational 1024, 1102
DESTINATION PC:
LOG ON:
Security 4624, 4625
TerminalServices-RemoteConnectionManager/Operational 1149
RemoteDesktopServices-RDPCoreTS /Operational 98, 131
TerminalServices-LocalSessionManager/Operational 21, 22, 25
LOG OFF:
Security 4634, 4647
TerminalServices-LocalSessionManager/Operational 23, 40

This list is by no means all-inclusive—there are others too—but this example will give us a good cross-section of what these activities will leave for additional or supporting evidence.

The Source Machine

Let’s begin with the source machine. There will be less there to see here, but there are events created when using the RDP client to connect to another computer, which can be very important. These events help verify other logged events on the destination machines and can help identify other systems that may have been compromised.

Event 4648

In the security log, an event gets logged with ID 4648 whenever an authorization takes place using explicit credentials. When that authentication is used for a remote system it looks something like this:

RDP Connection Event 4648

The important information we can get from this event are in the top three sections.

  1. The Subject section is the account logged into the source PC.
  2. The Account Whose Credentials Were Used section is self-explanatory: that is the account used when authenticating with the RDP Client to connect the remote machine.
  3. Target Server is the machine being connected to.

There are a few things to keep in mind when looking at 4648 events.

First, they get logged a lot—whenever explicit credentials are used. Most of the time, they will show as targeting local host as credentials were used locally, or other systems if credentials are used to access or connect to resources.

Second, which you’ve probably noticed, there is nothing in this event to signify that this authentication was for an RDP connection. That is exactly why it is important to correlate logs so that you can tie events from the destination machine to this time frame and verify the accuracy of the log. You can now be certain that this was the destination machine.

Finally, pay attention to the subject and account name under Account Whose Credentials Were Used. If you see a known-compromised account using additional accounts, you can identify additional compromised accounts and possibly verify that other authentication attacks have occurred. You could also then browse all events with ID 4648 around the same time to see if there are any others that look like they could have been connections to other workstations, gaining more evidence of lateral movement.

Events 1024 and 1102

For the next two events, we’ll look at reside in the TerminalServices-RDPClientOperational event log on the source machine. In the event viewer, you can find this log under Application and Services Logs Microsoft Windows TerminalServices-ClientActiveXCore.

These events have the IDs 1024 and 1102, and each has a specific, potentially useful, piece of information.

First, 1024 will usually appear in the logs a couple of seconds before our 4648 event from above. It shows us that the RDP client is attempting to connect to a remote machine or server. It will include the name of the machine, if it is available.

RDP Connection Event 1024

Second, 1102 will usually appear about 10 seconds (give or take a few) after the 1024 event. It will provide us with the IP address of the remote machine once it has initiated a connection with the destination.

RDP Connection Event 1102

Event 1102 likely won’t give us anything new, assuming we have identified the 4648 event from the security log. But, as I mentioned earlier, it is becoming more common for attackers to clear the security log in an attempt to cover their tracks.

It is always useful—and often critical—to have multiple places where corroborating evidence can be found. Having the IP address from 1102 will also be useful, especially if a machine name is not available.

Now, with that, let’s look at the destination machine. As this is the machine that the most activity is occurring on, we have quite a bit more to observe.

The Destination Machine

The destination machine is the machine that has been remotely accessed. It (hopefully) has quite a few logs available to review. Most likely, if logs have been tampered with or cleared, this is the machine they’ll do it on.

Events 4624 and 4625

To start, let’s take a quick look at our old friends 4624 and 4625. Now, I am sure most folks reading this know what these events look like, but I want to point out something about the Logon Type as it relates to RDP activity.

Here are two 4624 events. 4625 is, of course, just an authentication failure, meaning the username or password was wrong. But, the logon type is noteworthy.

RDP Connection Event 4624 type 7

In the first, on 9/29/2020, we see the account of pgreenman log in with a logon type of 10. We know type 10 is for a remote interactive logon, which is what we would expect to see. We know type 10 is for a remote interactive logon, which is what we would expect to see.

RDP Connection Event 4624 type 10

However, on the following day, we see the account log in with a logon type of 7. The connection was still an RDP connection, so why was it not logged as a Type 10? Type 7 logons are used for unlock events.

Likely, what has happened is that pgreenman’s account was not fully logged off; only the interactive session had ended, and there is likely no timeout to end disconnected sessions set in GPO. So, when he reconnected the following day, instead of registering as a new RDP login (type 10) it registered simply as an unlock of the session (Type 7).

This helps illustrate why it is important to keep in mind that we might not always see a type 10 logged for every RDP connection. There should, however, be one type 10 logon logged when the session is first initiated. However, that event could have been deleted. Or, the logs may have rolled over if there has been a session logged in for an extended time.

Event 1149

Now, let’s move on to some of the less commonly reviewed logs. Let’s look at event ID 1149 within the TerminalServices-RemoteConnectionManager/Operational log.

RDP Connection Event 1149

Event 1149 is logged when there is a successful RDP logon to the computer. Before Windows 7 and Windows Server 2012, 1149 would be logged for any initiation of an RDP connection, so it was not a useful indicator for an actual successful application of user credentials.

But, that has changed, and all modern OS versions will only log 1149 if the username in the event was successfully authenticated. It also includes the IP address of the source of the connection, which is useful information.

If an account is used and successfully authenticates but does not have permission to RDP to the computer due to other restrictions, event 1149 is not generated.

Events 98 and 131

Next, let’s look at events 98 and 131 in the RemoteDesktopServices-RDPCoreTS /Operational log. With these two events, what we’re seeing is a record of the acceptance and establishment of the TCP connection for the RDP session.

RDP Connection Event 98

RDP Connection Event 131

You’ll see several event 131s per 98. Some will be UDP and some TCP, as RDP can now utilize both. The evidence we have is still useful to note.

Again, it is always good to be able to find corroborating evidence in several places. To reiterate: we can see the IP address the connection is coming from, and by looking at the event 131s, we can see what ports were being used as well.

Other Events

Lastly, for the events that generate at connection of the RDP session, let’s review at some event IDs within the TerminalServices-LocalSessionManager/Operational log.

Here, the events we will look at are 21, 22, and 25. Each gets logged under a slightly different circumstance. Events 23 and 40 are others to note. We’ll cover those last, as they pertain to the logoff of the session.

As the name of the log implies, these events all pertain to the management of local sessions by Terminal Services.

Event 21

Our first event, ID 21, is registered when RDP successfully logs into a session.

RDP Connection Event 21

The event will log both the connected username and the session ID number assigned. The username here includes the domain and is the account used to log in, not necessarily the account logged into the source machine.

Event 22

The next event to note is 22. This contains much of the same information as 21, so nothing really new there. But it is registering the reception of the Shell start notification, which can be additional evidence of the interactive logon session, aka graphical interface of windows which RDP provides.

RDP Connection Event 22

Event 25

The last of the logon or connection events we’ll look at today is event 25. This event is logged when RDP is reconnecting to a session, like that type 7 logon we mentioned above. There was already a logged in session for the user, and then RDP reconnected to it. It could be that the session was local or a previous RDP session.

RDP Connection Event 25

Either way, we would have seen 4624 created with a type 7 logon. This event also includes the source IP address of the connection, which could be valuable if it was not available in the previously mentioned events.

Now, as always, we need to consider the full timeline of activity that was carried out by the attacker on the systems we are investigating. So not only should we look for logon and connection events, but also logoff events.

There are, of course, two events which will appear in the Security log, 4634 and 4647. These register the event when a user initiates a logoff (4647) and when the user is actually logged off (4634). You can glean some additional tidbits regarding whether the system was rebooted by comparing Logon IDs.

For the most part, that is what they will tell you, and they don’t indicate if the session was local or remote. But, if your security logs are intact, they can be helpful in filling out our understanding of the actions the attacker has taken.

However, as I have mentioned several times, the security log is a prime target for log manipulation and destruction, so we will want other places to gather this information. For that, we turn back to the TerminalServices-LocalSessionManager/Operational log and the two events I mentioned earlier: 23 and 40.

Event 40

First, let’s look at Event 40. This event is registered whenever a session is disconnected, so that could be an interruption or the user disconnecting or logging off. Within the event text, we are given a reason code, which gives us detail on the disconnection.

RDP Connection Event 40

Most often, you’ll see types 0, 5, 11, and 12, but there are definitions for all codes from 0 to 12.

  • Code 0 means that there is simply no additional information available for the disconnection.
  • Code 2 is similar to code 11; it is logged when an administrative tool was used to disconnect the session from another session.
  • Code 5 is registered when a user connects to the machine, forcing the disconnection of another current connection. It could be the same username used or that the system simply does not support multiple concurrent sessions.
  • Code 11 is registered when the disconnection was initiated by the user being disconnected from the session. This could be the user closing the RDP window or an administrative tool being used from the same session to force the disconnection, such as the logoff command in CMD or a batch file.
  • Code 12 is registered when the disconnection was initiated by the user logging off their session on the machine, such as logging out via the start menu.

Event 23

Finally, we have Event 23, which is registered when the session is logged off successfully.

RDP Connection Event 23

This would be logged after any log off scripts or other tasks are scheduled to be completed at logoff, and it shows that the session has truly come to an end. It, again, registers the user who was connected and the session ID that was associated.

What It All Means

With that, we have seen the timeline of these connections. We’ve followed from the initiating events on the source machine to the end of the session on the destination. From the information within these events, we can piece together a timeline of when a computer was accessed, from where, and for how long, even if the session may have lasted over several days and other connections.

Hopefully, taking the time to review these event IDs, what they can show, and how they relate will prove to be valuable when tracking down suspicious lateral movement. Or, maybe you just understand the event logs in relation to RDP a bit more.

This article was written by Tim of Team Ambush


This post is part of Team Ambush’s FRSecure Labs content. Check out their page to read more like it.

Explore FRSecure's Incident Response Services

Early in my DFIR career, I struggled with understanding how exactly to identify and understand all the RDP-related Windows Event Logs. I would read a few things here and there, think I understood it, then move on to the next case – repeating the same loop over and over again and never really acquiring full comprehension. That is until one day I finally got tired of repeating the same questions/research and just made a cheat sheet laying out the most common RDP-related Event ID’s that I’d encountered along with their relevance and descriptions. From that point on, as I sporadically encountered related questions/confusion from others in the community, I would simply refer to my cheat sheet to provide an immediate response or clarification – saving them from the hours of repeated questioning and research I had already done.

However, it seems the community continues to encounter the same struggle in identifying and understanding RDP-related Windows Event Log ID’s, where each is located, and even what some of them mean (no thanks to some of Microsoft’s very confusing documentation and descriptions). As such, I recently set out to try and find an easy route to the solution for this problem (i.e. hopefully find a single website to point to with all this information). Though I’ve found parts of the answer in posts here and there, each of them were missing parts of the puzzle (either missing ID’s, descriptions, explanations, and/or overall how they fit together in a chronological fashion). I will say JPCERTCC did an awesome job capturing a ton of information here, I just can’t quite decipher or discern the clear order of events and some appear out of order (at least how I have encountered them, but maybe I’m reading it wrong…). At any rate, as they say, necessity is the mother of invention.

So, I decided to create a blog post that I hope can serve as a succinct one-stop shop for understanding and identifying the most commonly encountered and empirically useful* RDP-related Windows Event Log ID’s/entries for tracking and investigating RDP usage on a Windows Vista+ endpoint. The Windows Event ID’s in the XP days were different than those in Vista+ Operating Systems. So, I decided to leave those out for now, but perhaps I will add them in the future.

*Yes, there are Event ID’s like 1146, 1147, and 1148 which look great in Microsoft’s documentation as a very useful source of information. However, I’ve yet to see (m)any of these commonly occurring in the wild.

I debated back and forth on the best way to sort/group these. Ultimately, in truly pragmatic fashion, I figured it would likely be most useful to sort them in the (chronological) order in which you might expect to find them. Ergo, the flow/section breakup is the following:

Network Connection
->-> Authentication
->-> Logon
->-> Session Disconnect/Reconnect
->-> Logoff

Network Connection

This section covers the first indications of an RDP logon – the initial network connection to a machine.

Log: Microsoft-Windows-Terminal-Services-RemoteConnectionManager/Operational

Log Location: %SystemRoot%System32WinevtLogsMicrosoft-Windows-TerminalServices-RemoteConnectionManager%4Operational.evtx

Event ID: 1149
Provider Name: Microsoft-Windows-Terminal-Services-RemoteConnectionManager
Description: “User authentication succeeded”
Notes: Despite this seemingly clear-cut description, this event actually DOES NOT indicate a successful user authentication in the sense that many might expect (e.g., successful input and acceptance of a username and password). Instead, “authentication” in this sense is referring to successful network authentication, as in someone successfully executed an RDP network connection to the target machine and it successfully responded and displayed a login window for the next step of entering credentials. For example, if I launched the RDP Desktop Connection program on my computer, input a target IP, and hit enter, it would simply display the target system’s screen and produce an 1149 Event ID indicating I had successfully connected to the target, WELL BEFORE I even entered any credentials. So, repeat after me, “An Event ID 1149 DOES NOT indicate successful authentication to a target, simply a successful RDP network connection”.
TL;DR: NOT AN AUTHENTICATION. Someone launched an RDP client, specified the target machine (possibly with a username and domain), and hit enter to make a successful network connection to the target. Nothing more, nothing less.


Authentication

This section covers the authentication portion of the RDP connection – whether or not the logon is allowed based on success/failure of username/password combo.

Log: Security

Log Location: %SystemRoot%System32WinevtLogsSecurity.evtx

Event ID: 4624
Provider Name: Microsoft-Windows-Security-Auditing
LogonType: Type 3 (Network) when NLA is Enabled (and at times even when it’s not) followed by Type 10 (RemoteInteractive / a.k.a. Terminal Services / a.k.a. Remote Desktop) OR Type 7 from a Remote IP (if it’s a reconnection from a previous/existing RDP session)
Description: “An account was successfully logged on”
Notes: I thought this one was pretty straight forward – just look for Type 10 logons for RDP. However, in a bit more research, I discovered that often a Type 3 logon (for NLA) will occur prior to the Type 10 logon. In addition, I also discovered that RDP’ing to a system of which you’d previously RDP’ed and not formally logged off/out would instead yield a Logon Type 7 logon versus the Logon Type 10 we’d expect. This makes sense in a way in that a Logon Type 7 (“This workstation was unlocked”) is essentially what is happening. However, to delineate this from non-RDP Type 7 logons in which a person was sitting at the machine and just unlocked the machine, we can look for remote non-local IP’s in the IpAddress field.
TL;DR: User successfully logged on to this system with the specified TargetUserName and TargetDomainName from the specified IpAddress.


Event ID: 4625
Provider Name: Microsoft-Windows-Security-Auditing
LogonType: Type 3 (Network) when NLA is Enabled (and at times even when it’s not) and/or Type 10 (RemoteInteractive / a.k.a. Terminal Services / a.k.a. Remote Desktop)
Description: “An account failed to log on”
Notes: Why do we care about failures? Well, this is helpful in identifying (brute force) failure attempts and seeing when/where an attacker may be attempting stolen/compromised credentials. The Status/Sub Status Code will also be helpful in delineating legitimate failures (e.g. “expired password”) as well as possibly providing insight into attacker activity (e.g. repetitive “user name does not exist” codes could indicate brute force guessing by a tool and/or a more targeted lack of username knowledge/awareness in the environment by the attacker).
TL;DR: User failed to log on to this system with the specified TargetUserName and TargetDomainName from the specified IpAddress.

#ProTip(s):

1) When NLA is enabled, a failed RDP logon (due to wrong username, password, etc.) will result in a 4625 Type 3 failure. When NLA is not enabled, you *should* see a 4625 Type 10 failure.

2) Both of these entries also contain a “SubjectLogonID” or a “TargetLogonID” field. This ID is unique for each logon session and is also present in various other Event Log entries, making it theoretically useful for tracking/delineating a specific user’s activities, particularly on systems allowing multiple logged on users. However, do take note that a unique *LogonID is assigned for each session, meaning if a user connects, then disconnects (without logging out, thus simply ending the current session), then reconnects (i.e. starting a new session), they will be assigned a different unique *LogonID. All to say that a single user(name) may have multiple unique *LogonID’s to track depending how many sessions they’ve instantiated, not to mention Windows makes it very confusing sometimes with multiple 4624’s with different *LogonID’s for the same session. So, YMMV.

Additional References:

David Cowen’s Forensic Lunch Test Kitchen – RDP Testing (1 , 2 , 3)
Microsoft Forum Answer Re: RDP 4624 Type 3 Logons (link)

Logon

This section covers the ensuing (post-authentication) events that occur upon successful authentication and logon to the system.

Log: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational

Log Location: %SystemRoot%System32WinevtLogsMicrosoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx

Event ID: 21
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Remote Desktop Services: Session logon succeeded:”
Notes: This typically immediately precedes an Event ID 22 when the “Source Network Address” contains a remote IP address. Note that a “Source Network Address” of “LOCAL” simply indicates a local logon and does NOT indicate a remote RDP logon. this event with a “Source Network Address” of “LOCAL” will also be generated upon system (re)boot/initialization (shortly before the proceeding associated Event ID 22) . For remote RDP logons, take note of the SessionID as a means of tracking/associating additional Event Log activity with this user’s RDP session.
TL;DR: Indicates successful RDP logon and session instantiation, so long as the “Source Network Address” is NOT “LOCAL”.

Event ID: 22
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Remote Desktop Services: Shell start notification received:”
Notes: This typically immediately proceeds an Event ID 21. Note that a “Source Network Address” of “LOCAL” simply indicates a local logon and does NOT indicate a remote RDP logon. This event with a “Source Network Address” of “LOCAL” will also be generated upon system (re)boot/initialization (shortly after the preceding associated Event ID 21).
TL;DR: Indicates successful RDP logon and shell (i.e. Windows GUI Desktop) start, so long as the “Source Network Address” is NOT “LOCAL”.

Session Disconnect/Reconnect

This section covers the various session disconnect/reconnect events that might occur due to either system (idle), network (network disconnect), or purposeful user (X out of the RDP window, Start -> Disconnect, Kicked off by another user, etc.) action.

Log: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational

Log Location: %SystemRoot%System32WinevtLogsMicrosoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx

Event ID: 24
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Remote Desktop Services: Session has been disconnected:”
Notes: The user has disconnected from an RDP session, when the “Source Network Address” contains a remote IP address. A “Source Network Address” of “LOCAL” simply indicates a local session disconnection and does NOT indicate a remote RDP disconnection. Note the “Source Network Address” for the source of the RDP connection. This is typically paired with an Event ID 40. Also take note of the SessionID as a means of tracking/associating additional Event Log activity with this user’s RDP session.
TL;DR: The user has disconnected from an RDP session, so long as the “Source Network Address” is NOT “LOCAL”.


Event ID: 25
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Remote Desktop Services: Session reconnection succeeded:”
Notes: The user has reconnected to an RDP session, when the “Source Network Address” contains a remote IP address. A “Source Network Address” of “LOCAL” simply indicates a local session reconnection and does NOT indicate a remote RDP session reconnection. Note the “Source Network Address” for the source of the RDP connection. This is typically paired with an Event ID 40. Take note of the SessionID as a means of tracking/associating additional Event Log activity with this user’s RDP session.
TL;DR: The user has reconnected to an existing RDP session, so long as the “Source Network Address” is NOT “LOCAL”.


Event ID: 39
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Session <X> has been disconnected by session <Y>”
Notes: This indicates that a user has formally disconnected from an RDP session via purposeful Disconnect (e.g., via the Windows Start Menu Disconnect option) versus simply X’ing out of the RDP window. Cases where the Session ID of <X> differs from <Y> may indicate a separate RDP session has disconnected (i.e. kicked off) the given user.
TL;DR: The user formally disconnected from the RDP session.


Event ID: 40
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Session <X> has been disconnected, reason code <Z>”
Notes: In true Microsoft fashion, although the description is always “Session has been disconnected”, these events also indicate/correlate to reconnections, not just disconnections. The most helpful information here is the Reason Code (a function of the IMsRdpClient::ExtendedDisconnectReason property), the list of which can be seen here (and this pairs it with the codes to make it easier to read). Below are some examples of codes I encountered during my research.
0 – “No additional information is available.” (Occurs when a user informally X’es out of a session, typically paired with Event ID 24)
5 – “The client’s connection was replaced by another connection.” (Occurs when a user reconnects to an RDP session, typically paired with an Event ID 25)
11 – “User activity has initiated the disconnect.” (Occurs when a user formally initiates an RDP disconnect, for example via the Windows Start Menu Disconnect option.)
TL;DR: The user disconnected from or reconnected to an RDP session.


Log: Security

Log Location: %SystemRoot%System32WinevtLogsSecurity.evtx

Event ID: 4778
Provider Name: Microsoft-Windows-Security-Auditing
Description: “A session was reconnected to a Window Station.”
Notes: Occurs when a user reconnects to an existing RDP session. Typically paired with Event ID 25. The SessionName, ClientAddress, and LogonID can all be useful for identifying the source and associated activity.
TL;DR: The user reconnected to an existing RDP session.


Event ID: 4779
Provider Name: Microsoft-Windows-Security-Auditing
Description: “A session was disconnected from a Window Station.”
Notes: Occurs when a user disconnects from an RDP session. Typically paired with Event ID 24 and likely Event ID’s 39 and 40. The SessionName, ClientAddress, and LogonID can all be useful for identifying the source and associated activity.
TL;DR: The user disconnected from from an RDP session.


Logoff

This section covers the events that occur after a purposeful (Start -> Disconnect, Start -> Logoff) logoff.

Log: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational

Log Location: %SystemRoot%System32WinevtLogsMicrosoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx

Event ID: 23
Provider Name: Microsoft-Windows-TerminalServices-LocalSessionManager
Description: “Remote Desktop Services: Session logoff succeeded:”
Notes: The user has initiated a logoff. This is typically paired with an Event ID 4634 (logoff). Take note of the SessionID as a means of tracking/associating additional Event Log activity with this user’s RDP session. This event with a will also be generated upon a system shutdown/reboot.
TL;DR: The user initiated a formal system logoff (versus a simple session disconnect).


Log: Security

Log Location: %SystemRoot%System32WinevtLogsSecurity.evtx

Event ID: 4634
Provider Name: Microsoft-Windows-Security-Auditing
LogonType: 10 (RemoteInteractive / a.k.a. Terminal Services / a.k.a. Remote Desktop) OR Type 7 from a Remote IP (if it’s a reconnection from a previous/existing RDP session)
Description: “An account was logged off.”
Notes: These occur whenever a user simply disconnects from an RDP session or formally logs off (via Windows Start Menu Logoff). This is typically paired with an Event ID 21 (RDP Session Logoff). I’ve also discovered these will also be paired (i.e. occur at the same time) with successful authentications (Event ID 4624). Why, I have no idea.
TL;DR: A user disconnected from, or logged off, an RDP session.


Event ID: 4647
Provider Name: Microsoft-Windows-Security-Auditing
Description: “User initiated logoff:”
Notes: Occurs when a user initiates a formal system logoff and is not necessarily RDP specific. You will need to use some reasoning and temporal analysis to understand if/when it is related to a system logoff via an RDP session or is from a local interactive session as there is no LogonType associated specify which it is.
TL;DR: The user initiated a formal logoff (NOT a simple disconnect).


Log: System

Log Location: %SystemRoot%System32WinevtLogsSystem.evtx

Event ID: 9009
Provider Name: Desktop Window Manager
Description: “The Desktop Window Manager has exited with code (<X>).”
Notes: Occurs when a user formally closes an RDP connection and indicates the RDP desktop GUI has been shut down as a result. This is useful to identify a closed/finalized RDP connection. Though, this event is not always produced for reasons I do not know.
TL;DR: A user has closed out an RDP connection.


Wrap-Up

Hopefully that provides a little better insight into some of the most common and (IME) most empirically useful RDP-related Event logs, when/where you might encounter them, what they mean, what they look like, and (most importantly) how they all fit together.

As a result of this post, Richard Davis (@richarddavisg, @13CubedDFIR) of 13Cubed on YouTube has also put together an RDP flow chart that is very helpful in visualizing the expected (though, not guaranteed) flow of these logs. Feel free to check out his short video walkthrough as well.

In this article we will take a look at the features of Remote Desktop Protocol (RDP) connection auditing and log analysis in Windows. Typically, it is useful when investigating various incidents on Windows servers when a system administrator is required to provide information about what users logged on to the server, when he logged on and off, and from which device (name or IP address) the RDP user was connecting.

Remote Desktop Connection Events

Like other events, the Windows RDP connection logs are stored in the event logs. The Windows logs contain a lot of information, but it can be difficult to find the right event quickly. When a user remotely connects to a Windows server, many events are generated in the Windows logs. We will take a look at the following:

  • Network Connection
  • Authentication
  • Logon
  • Session Disconnect/Reconnect
  • Logoff

Network Connection Events

Network Connection connects user’s RDP client with the Windows server. That logs EventID – 1149 (Remote Desktop Services: User authentication succeeded). The presence of this event does not indicate successful user authentication. This log can be found at Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ Terminal-Services-RemoteConnectionManager ⇒ Operational. You can filter this log by right clicking on Operational log ⇒ Selecting “Filter Current Log” and type in EventID 1149.

Event log filtering

Filtering the log for EventID 1149

The result is a list with the history of all network RDP connections to this server. As you can see, the log file contains the username, domain (When Network Level Authentication (NLA) authentication is used), and IP address of the computer from which the RDP connection is made.

EventID 1149

EventID 1149 output

Authentication Events

User authentication can be successful or unsuccessful on the server. Navigate to Windows logs ⇒ Security. We are interested in logs with EventID – 4624 (An account was successfully logged on) or 4625 (An account failed to log on). Pay attention to the LogonType value in the event. LogonType – 10 or 3 indicates a new logon to the system. If LogonType is 7, it indicates re-connection to an existing RDP session.

EventID 4624

EventID 4624

The username of the connecting account is written in the Account Name field, his computer name is written in Workstation Name, and the IP address in Source Network Address.

Take a look at TargetLogonID field, which is a unique user session identifier that can be used to track further activity of this user. However, if a user disconnects from the RDP session and reconnects to the session again, the user will be issued a new TargetLogonID (although the RDP session remains the same).

You can get a list of successful authentication events over RDP (EventID 4624) using the following 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 Events

RDP logon is the event that appears after successful user authentication. Log entry with EventID – 21 (Remote Desktop Services: Session logon succeeded). This log can be found in Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ TerminalServices-LocalSessionManager ⇒ Operational. As you can see here you can see the RDP Session ID for the user.

RDS EventID 21

Remote Desktop Services EventID 21

Remote Desktop Services: Shell start received” details in EventID 21 means that the Explorer shell has been successfully launched in the RDP session.

Session Disconnect and Reconnect Events

Session Disconnect/Reconnect events have different codes depending on what caused the user to end the session, for example disable by inactivity, selecting “Disconnect” in Start menu, RDP session drop by another user or administrator, etc. These events can be found in Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ TerminalServices-LocalSessionManager ⇒ Operational. Let’s take a look at the RDP events that may be of interest:

  • EventID – 24 (Remote Desktop Services: Session has been disconnected) – the user has disconnected from the RDP session.
  • EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – The user has reconnected to his existing RDP session on the server.
  • EventID – 39 (Session A has been disconnected by session B) – user disconnected from his RDP session by selecting the appropriate menu item (not just closed the RDP client window by clicking on “x” in the top right corner). If the session IDs are different, then the user has been disconnected by another user or administrator.
  • EventID – 40 (Session A has been disconnected, reason code B). Here you should look at the reason code for the disconnection in the event. For example:
    • Reason code 0 (No additional information is available) – usually indicates that the user just closed the RDP client window.
    • Reason code 5 (The client’s connection was replaced by another connection) – the user re-connected to his old session.
    • Reason code 11 (User activity has the disconnect) – the user clicked the Disconnect button on the menu.
  • EventID – 4778 in Windows log ⇒ Security (A session was reconnected to a Window Station). The user re-connected to an RDP session (the user is given a new LogonID).
  • EventID 4799 in Windows Logon ⇒ Security (A session was reconnected to a Window Station). Disconnection from an RDP session.

Logoff Events

Logoff logs track the user disconnection from the system. In the Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ TerminalServices-LocalSessionManager ⇒ Operational logs we can find EventID 23. In this case in Security log we need to search for EventID 4634 (An account was logged off).

logoff EventID 23

RDP session logoff EventID 23

Event 9009 (The Desktop Window Manager has exited with code (x)) in the System log shows that the user initiated the end of the RDP session and the user’s window and graphical shell were terminated. Below is a small PowerShell that uploads the history of all RDP connections for the current day from the Remote Desktop Service server. The table below shows the connection time, client IP address, and RDP username (you can include other logon types in the report if necessary).

Get-EventLog -LogName Security -after (Get-date -hour 0 -minute 0 -second 0)| ?{(4624,4778) -contains $_.EventID -and $_.Message -match 'logon type:s+(10)s'}| %{
(new-object -Type PSObject -Property @{
TimeGenerated = $_.TimeGenerated
ClientIP = $_.Message -replace '(?smi).*Source Network Address:s+([^s]+)s+.*','$1'
UserName = $_.Message -replace '(?smi).*Account Name:s+([^s]+)s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*Account Domain:s+([^s]+)s+.*','$1'
LogonType = $_.Message -replace '(?smi).*Logon Type:s+([^s]+)s+.*','$1'
})
} | sort TimeGenerated -Descending | Select TimeGenerated, ClientIP `
, @{N='Username';E={'{0}{1}' -f $_.UserDomain,$_.UserName}} `
, @{N='LogType';E={
switch ($_.LogonType) {
2 {'Interactive - local logon'}
3 {'Network conection to shared folder)'}
4 {'Batch'}
5 {'Service'}
7 {'Unlock (after screensaver)'}
8 {'NetworkCleartext'}
9 {'NewCredentials (local impersonation process under existing connection)'}
10 {'RDP'}
11 {'CachedInteractive'}
default {"LogType Not Recognised: $($_.LogonType)"}
}
}}

Exporting RDP logs

Sometimes it is needed to export RDP logs into Excel table, in this case you can upload any Windows log to a text file and afterwards import it into Excel. You can export the log from the Event Viewer console or from the command line:

WEVTUtil query-events Security > c:pssecurity_log.txt

Or:

get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:psrdp-log.txt -Encoding UTF8 

A list of the current RDP sessions on the server can be displayed as a command “Qwinsta”

qwinsta command output

qwinsta output

The command returns as session identifier, username and status (Active/Disconnect). This command is useful when you need to determine the RDP session ID of a user during a shadow connection.

After defining a Session ID you can list running processes in a particular RDP session:

qprocess command output

qprocess output

So here are the most common ways to view RDP connection logs in Windows.

Понравилась статья? Поделить с друзьями:
  • Лицензия операционной системы windows server 2019 standard коробочная версия
  • Лицензия на установку windows 10 что это
  • Лицензия на установку windows 10 сколько стоит
  • Логи rdp подключений windows server 2008
  • Лицензия на установку windows 10 скачать бесплатно