В этой статье мы рассмотрим, как получить и проанализировать логи 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.
- 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).
С помощью 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 подключений к данному серверу. В событии содержится имя пользователя, домен (если используется NLA аутентификация, при отключенном NLA текст события выглядит иначе) и IP адрес компьютера пользователя.
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 скриптом (см. статью).
При этом имя пользователя содержится в описании события в поле 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
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 – события отключения и переподключения к сессии имеют разные коды в зависимости от того, что вызвало отключение пользователя (отключение по неактивности, заданному в таймаутах для 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).
При этом в журнале 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).*\s\sAccount Name:\s+([^\s]+)\s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*\s\sAccount 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 подключений из журнала в CSV файл (для дальнейшего анализа в таблице Excel). Экспорт журнала можно выполнить из консоли Event Viewer (при условии что логи не очищены) или через командную строку:
WEVTUtil query-events Security > c:\ps\security_log.txt
Или с помощью PowerShell:
get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:\ps\rdp-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
Другие события, связанные с подключениями пользователей на 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 сессии пользователя при теневом подключении.
Список запущенных процессов в конкретной RDP сессии (указывается ID сессии):
qprocess /id:157
Логи 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.
Следующий 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
Скрипт возвращает 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 server 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 and desktop editions (Windows 11 and 10).
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
- Network Connection;
- Authentication;
- Logon;
- Session Disconnect/Reconnect;
- 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).
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
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.
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).
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
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
). These 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: 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.
- reason code 0 (
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”.
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).*\s\sAccount Name:\s+([^\s]+)\s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*\s\sAccount 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)"}
}
}}
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:\ps\rdp_security_log.txt
Or with PowerShell:
get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:\ps\rdp_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
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 the 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.
You can display the list of the running processes in the specific RDP session (the session ID is specified):
qprocess /id:5
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.
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
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.
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%\System32\Winevt\Logs\Microsoft-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%\System32\Winevt\Logs\Security.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%\System32\Winevt\Logs\Microsoft-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%\System32\Winevt\Logs\Microsoft-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%\System32\Winevt\Logs\Security.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%\System32\Winevt\Logs\Microsoft-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%\System32\Winevt\Logs\Security.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%\System32\Winevt\Logs\System.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.
Skip to content
Published on July 10, 2023
Last updated on March 3, 2025
What Is It?
The TerminalServices-LocalSessionManager log contains entries about the allocation of local sessions, which are used for both local and remote interactive logins. It is updated by the Local Session Manager part of Remote Desktop Services (previously called Terminal Services).
What Does It Contain?
This log contains audit information associated with the Local Session Manager (LSM). Though similarly named, local sessions are different from logon sessions.
- A local session stores the logon sessions, desktop layout, etc. for a user’s interactive login (remote or local).
- A logon session is a security concept that defines the access that processes have based on the account that was authenticated.
The Local Session Manager is responsible for creating, destroying, and reconnecting local sessions.
- Local sessions are created when a user logs in for the first time after a logoff or a system reboot.
- Local sessions are closed when a user logs out.
- Local sessions are reconnected when a user switches between local and remote logins or when the remote login disconnects.
- Microsoft calls this Fast User Switching. Learn more about sessions here.
The log contains many types of events, such as when local sessions:
- Are created
- Are closed
- Are reconnected
- Are disconnected
A list of events is given below.
Relevance to DFIR?
This event log is useful when investigating inbound Windows RDP remote logins and local interactive logins. RDP can be used by attackers to remotely control a system once they have account credentials.
Note that if the attackers used remote access software other than Windows RDP, then this log will not have entries for those logins.
Found a Suspicious Logon?
Use our guide to analyzing suspicious logons with a free trial of Cyber Triage to quickly confirm if it’s malicious.
Storage Details
The event log file can be found at:
SystemRoot%\System32\Winevt\Logs\Microsoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx
It can be disabled by setting the
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Channels\Microsoft-Windows-TerminalServices-LocalSessionManager/Operational/Enabled registry key to “0”.
Inbound Logon Events
The notable event types in there include:
- Event ID 21 – Session logon succeeded
- Event ID 22 – Shell start notification received
- Event ID 23 – Session logoff succeeded
- Event ID 24 – Session has been disconnected
- Event ID 25 – Session reconnection succeeded
- Event ID 39 – Session has been disconnected by another session
- Explicit disconnect (same session IDs) or kicked off (diff session IDs)
- Event ID 40 – Session disconnect with reason
- Can also be for reconnect
Cyber Triage Status
Cyber Triage collects this log file and parses it to make Inbound Logon sessions.
Sources
- https://learn.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-terminalservices-localsessionmanager
- https://ponderthebits.com/2018/02/windows-rdp-related-event-logs-identification-tracking-and-investigation
- https://dfironthemountain.wordpress.com/2019/02/15/rdp-event-log-dfir/
- https://learn.microsoft.com/en-us/windows/win32/shell/fast-user-switching
- https://www.microsoftpressstore.com/articles/article.aspx?p=2224373&seqNum=7
- https://digitalforensicsurvivalpodcast.com/2023/01/31/dfsp-363-rdp-forensics/
- https://openxmldeveloper.org/uncovering-the-role-of-lsm-exe-how-it-helps-manage-windows-operating-systems/
Мониторинг внешнего входа и выхода пользователей Windows
Данные будем брать из Журнал событий (англ. Event Log)
Панель управления\Все элементы панели управления\Администрирование\Просмотр событий
или (Win+R) команду eventvwr.msc
eventlog-Microsoft-Windows-TerminalServices-LocalSessionManager-Operational
LSM — Local Session Manager
RCM — Remote Connection Manager
Запрос для Ключа eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip]
- eventlog-Microsoft-Windows-TerminalServices-LocalSessionManager-Operational
Пример Просмотр и анализ логов RDP подключений в Windows
Ключ в zabbix будет использоваться eventlog
eventlog[имя,<регулярное выражение>,<важность>,<источник>,<eventid>,<макс. кол-во строк>,<режим>]
eventlog[имя»Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,<регулярное выражение>пропускаем пусто,<важность>пропускаем пусто,<источник>пропускаем пусто,<eventid>^(21|23|24|25)$,<макс. кол-во строк>пропускаем пусто,<режим>skip]
skip — пропустить обработку старых данных
eventlog[имя,<регулярное выражение>,<важность>,<источник>,<eventid>,<макс. кол-во строк>,<режим>]
Мониторинг журналов событий.
Журнал (лог)
имя — имя журнала событий
регулярное выражение — регулярное выражение описывающее требуемый шаблон содержимого
важность — регулярное выражение описывающее важность
Параметр может принимать следующие значения:
“Information”, “Warning”, “Error”, “Critical”, “Verbose” (начиная с Zabbix 2.2, работающих на Windows Vista или на более новых версиях)
источник — регулярное выражение, описывающее идентификатор источника (регулярное выражение поддерживается начиная с версии Zabbix 2.2.0)
eventid — регулярное выражение описывающее идентификатор(ы) событий
макс. кол-во строк — максимальное количество новых строк в секунду, которое агент будет отправлять Zabbix серверу или прокси. Этот параметр заменяет значение ‘MaxLinesPerSecond’ в zabbix_agentd.win.conf
режим — возможные значения:
all (по умолчанию), skip — пропустить обработку старых данных (влияет только на недавно созданные элементы данных).
Элемент данных должен быть настроен активной проверкой.
Примеры:
⇒ eventlog[Application]
⇒ eventlog[Security,,»Failure Audit»,,529|680]
⇒ eventlog[System,,»Warning|Error»]
⇒ eventlog[System,,,,^1$]
⇒ eventlog[System,,,,@TWOSHORT] — здесь используется ссылка на пользовательское регулярное выражение с именем TWOSHORT (заданное с типом Результат ИСТИНА, само выражение равно ^1$|^70$).
Обратите внимание, агент не может отправлять события из «Пересланные события» журнала.
Параметр режим поддерживается начиная с версии 2.0.0.
“Windows Eventing 6.0” поддерживается начиная с Zabbix 2.2.0.
Обратите внимание, что выбор не журнального типа информации для этого элемента данных приведет к потере локального штампа времени, а также важности журнала и информации о источнике.
Смотрите дополнительную информацию о мониторинге файлов журналов.
СПЕЦИФИЧНЫЕ КЛЮЧИ ЭЛЕМЕНТОВ ДАННЫХ
Триггер
logeventid
Проверка, совпадает ли ID события последней записи из журнала указанному регулярному выражению.
шаблон — регулярное выражение описывающее требуемый шаблон, в формате расширенных регулярных выражений POSIX.
Поддерживаемые типы значений: log
Возвращает:
0 — не совпадает
1 — совпадает
Изначально шаблон был взят с Windows Server Login monitor далее путь на гитхаб Server-Login-monitor-Zabbix
Для начала оригинальный шаблон автора который был скачен с гитхаба
# Server-Login-monitor-Zabbix
uses Microsoft-Windows-TerminalServices-LocalSessionManager windows log to find logins and logouts to server.
and fires alarm when a user logs in to a server
Simply import to zabbix and add the template to desired hosts.
#Сервер-Логин-монитор-Zabbix
использует журнал Windows Microsoft-Windows-TerminalServices-LocalSessionManager для поиска логинов и выходов на сервер.
и подает сигнал тревоги, когда пользователь входит на сервер
Просто импортируйте в zabbix и добавьте шаблон на желаемые хосты.
Имя шаблона Windows external login monitor
Группы Windows
Описание Monitor non administrator logins on server
Макросы
{$HIDELOGINS} => Administrator
(не проверять, не выводить триггер когда заходит пользователь Administrator)
- Windows external login monitor
Группы элементов данных
Log
RDP
Элементы данных
Имя Login to Remote desktop
Тип Zabbix агент (активный)
Ключ eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23)$,,skip]
Тип информации Журнал (Лог)
Интервал обновления 15s
Период хранения истории 90d
Формат времени в журнале (логе) ddMMyyyy:hhmmss
Группы элементов данных
Log
RDP
Описание Monitor RDP login and logout
Активировано V
Предобработка
Шаги предобработки Имя Регулярное выражение Параметры User: (.*)\n Вывод \1
Для Русскоязычных систем Windows в Логе вместо User по Русскому пишется Пользователь получаем
Шаги предобработки Имя Регулярное выражение Параметры Пользователь: (.*)\n Вывод \1
- Элемент данных Windows external login monitor
Триггер
Имя {ITEM.LASTVALUE1} RDP login
Важность Высокая
Выражение проблемы
{Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23)$,,skip].logeventid(21)}=1
Генерация ОК событий Выражение восстановления
{Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23)$,,skip].logeventid(21)}=0
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание Fires alarm unless RDP login is administrator
Активировано V
- Триггер Windows external login monitor.jpg
Скачать шаблон
Далее первые изменения в шаблоне
Переведён полностью на Русский язык
Добавлены описания
Добавлен триггер на повторный вход 25
Имя шаблона Windows external login monitor
Видимое имя Монитор внешнего входа Windows
Описание Monitor non administrator logins on server
Мониторинг Логинов без прав администратора на сервере
Макросы
{$HIDELOGINS} => No я решил показывать все входы, не скрывая
- Windows external login monitor rus.jpg
Группы элементов данных
LOG-RDP&Local
Элементы данных
Имя Вход на удаленный рабочий стол
Тип Zabbix агент (активный)
Ключ eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip]
Тип информации Журнал (Лог)
Интервал обновления 15s
Период хранения истории 90d
Формат времени в журнале (логе) ddMMyyyy:hhmmss
Группы элементов данных
LOG-RDP&Local
Описание
Login to Remote desktop
Monitor RDP login and logout
Вход на удаленный рабочий стол
Монитор РДП вход и выход
17 — ошибка Не удалось запустить службу удаленного рабочего стола
21 — успешный Вход
22 — получено уведомление о запуске оболочки
23 — выход из сеанса
24 — отключен
25 — успешное пере подключение
Скрыть вход добавить макрос {$HIDELOGINS} Administrator
Активировано V
Предобработка
Для Русскоязычных систем Windows в Логе вместо User по Русскому пишется Пользователь получаем
Шаги предобработки Имя Регулярное выражение Параметры Пользователь: (.*)\n Вывод \1
- Элемент данных Windows external login monitor rus.jpg
Триггеры 2
Имя {ITEM.LASTVALUE1} RDP login
Важность Информация
Выражение проблемы {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip].logeventid(21)}=1
Генерация ОК событий Выражение восстановления
Выражение восстановления {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip].logeventid(21)}=0
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание
Fires alarm unless RDP login is administrator
21 — успешный Вход
Пожары сигнализации, если RDP логин администратора
Активировано V
- Триггер Windows external login monitor rus.jpg
Имя {ITEM.LASTVALUE1} RDP login povtor
Важность Информация
Выражение проблемы {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip].logeventid(25)}=1
Генерация ОК событий Выражение восстановления
Выражение восстановления {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip].logeventid(25)}=0
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание
Fires alarm unless RDP login is administrator
25 — успешное переподключение
Пожары сигнализации, если RDP логин администратора
Активировано V
- Триггер 2 Windows external login monitor rus.jpg
Скачать Шаблон
Дальнейшие доработки
Мало инфы в триггере 1.Пользователь который подключился 2.IP-адресс откуда подключился 3.Код Сеанса 4.Имя ПК с которого выполнено подключение
Отключенные пользователи которые не завершили сеанс, а просто его закрыли! Корректно нужно завершать сеанс, так же нужно проверять.
Сперва текущий актуальный шаблон на 12.01.2021, ниже как это делалось какие проблемы возникали и тд.
Скачать
Скачать
19.08.2022
Для элемента данных «Получаем предыдущее значение для Windows LSM»
если Windows включен но никто не заходил данные пустые строки нет и элемент уходит в ошибку что тип не числовой, в предобработке при пустом значении делаем 0.
- Если пустое значение а тип числовой делаем 0
Имя шаблона Windows external login monitor
Видимое имя Монитор внешнего входа Windows
Группы Windows и Windows Server
Описание
Monitor non administrator logins on server
Мониторинг Логинов без прав администратора на сервере
Макрос
{$HIDELOGINS} => No
- Шаблон Монитор внешнего входа Windows.jpg
Группы элементов данных LOG-RDP&Local
Элементы данных 5
- Элементы данных Монитор внешнего входа Windows
Элемент данных
Имя Вход в Windows LSM
Тип Zabbix агент (активный)
Ключ eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip]
Тип информации Журнал (лог)
Интервал обновления 15s
Период хранения истории Storage period 31d
Формат времени в журнале (логе) ddMMyyyy:hhmmss
Группы элементов данных LOG-RDP&Local
Описание
Login to Remote desktop
Monitor RDP login and logout
Вход на удаленный рабочий стол
Монитор РДП вход и выход
17 — ошибка Не удалось запустить службу удаленного рабочего стола
21 — успешный Вход
22 — получено уведомление о запуске оболочки
23 — выход из сеанса
24 — отключен
25 — успешное переподключение
39 — (Session <A> has been disconnected by session <B>) – пользователь сам отключился от своей RDP сессии, выбрав соответствующий пункт меню (а не просто закрыл окно RDP клиента).
Если идентификаторы сессий разные, значит пользователя отключил другой пользователь (или администратор).
40 — Здесь нужно смотреть на код причины отключения в событии. Например:
Описание: «Сеанс <X> был отключен, код причины <Z>»
Сенас * был отключен, код причины 0
reason code 0 (No additional information is available)– обычно говорит о том, что пользователь просто закрыл окно RDP клиента, обычно в паре с идентификатором события 24
reason code 1 Отключение было инициировано административным инструментом на сервере в другом сеансе.
reason code 2 Отключение произошло из-за принудительного выхода из системы, инициированного административным инструментом на сервере в другом сеансе.
reason code 3 Таймер ограничения сеанса простоя на сервере истек.
reason code 4 Таймер ограничения активных сеансов на сервере истек.
reason code 5 (The client’s connection was replaced by another connection) – пользователь переподключился к своей старой сессии.
Сенас * был отключен, код причины 5 — Другой пользователь подключился к серверу, принудительно отключив текущее соединение. «Соединение клиента было заменено другим соединением». (Происходит, когда пользователь повторно подключается к сеансу RDP, обычно в паре с идентификатором события 25)
reason code 6 На сервере закончились доступные ресурсы памяти.
reason code 7 Сервер отказал в соединении.
reason code 8 Сервер отказал в соединении из соображений безопасности.
reason code 9 Пользователь не может подключиться к серверу из-за недостаточных прав доступа.
reason code 10 Сервер не принимает сохраненные учетные данные пользователя и требует, чтобы пользователь вводил свои учетные данные для каждого подключения.
reason code 11 (User activity has initiated the disconnect) – пользователь сам нажал на кнопку Disconnect в меню (Пуск отключение).
Отключение было инициировано пользователем, отключившим свой сеанс на сервере, или инструментом администрирования на сервере.
reason code 12 Отключение было инициировано пользователем, завершившим сеанс на сервере.
Сенас * был отключен, код причины 12 — Отключение было инициировано пользователем, завершившим сеанс на сервере
Определяет расширенную информацию о причине отключения элемента управления
Windows Vista — Server 2008 билиотека MsTscAx.dll
typedef enum _ExtendedDisconnectReasonCode {
exDiscReasonNoInfo = 0, Никакой дополнительной информации нет.
exDiscReasonAPIInitiatedDisconnect = 1, Приложение инициировало отключение.
exDiscReasonAPIInitiatedLogoff = 2, Приложение вышло из системы клиента.
exDiscReasonServerIdleTimeout = 3, Сервер отключил клиента, потому что клиент бездействовал в течение периода времени, превышающего назначенный период ожидания.
exDiscReasonServerLogonTimeout = 4, Сервер отключил клиента, поскольку клиент превысил период, отведенный для подключения.
exDiscReasonReplacedByOtherConnection = 5, Подключение клиента было заменено другим подключением.
exDiscReasonOutOfMemory = 6, Нет свободной памяти.
exDiscReasonServerDeniedConnection = 7, Сервер отказал в соединении.
exDiscReasonServerDeniedConnectionFips = 8, Сервер отказал в соединении из соображений безопасности.
exDiscReasonServerInsufficientPrivileges = 9, Сервер отказал в соединении из соображений безопасности.
exDiscReasonServerFreshCredsRequired = 10, Требуются новые учетные данные.
exDiscReasonRpcInitiatedDisconnectByUser = 11, Действия пользователя привели к отключению
exDiscReasonLogoffByUser = 2, Пользователь вышел из системы, отключив сеанс.
exDiscReasonLicenseInternal = 256, Ошибка внутреннего лицензирования.
exDiscReasonLicenseNoLicenseServer = 257, Сервер лицензий недоступен.
exDiscReasonLicenseNoLicense = 258, Действующей лицензии на программное обеспечение не было.
exDiscReasonLicenseErrClientMsg = 259, Удаленный компьютер получил недействительное лицензионное сообщение.
exDiscReasonLicenseHwidDoesntMatchLicense = 260, Идентификатор оборудования не соответствует идентификатору, указанному в лицензии на программное обеспечение.
exDiscReasonLicenseErrClientLicense = 261, Ошибка клиентской лицензии.
exDiscReasonLicenseCantFinishProtocol = 262, Проблемы с сетью возникли во время протокола лицензирования.
exDiscReasonLicenseClientEndedProtocol = 263, Клиент преждевременно прервал лицензионный протокол.
exDiscReasonLicenseErrClientEncryption = 264, Сообщение о лицензировании было зашифровано неправильно.
exDiscReasonLicenseCantUpgradeLicense = 265, Не удалось обновить или продлить лицензию на клиентский доступ локального компьютера.
exDiscReasonLicenseNoRemoteConnections = 266, Удаленный компьютер не имеет лицензии на прием удаленных подключений.
exDiscReasonLicenseCreatingLicStoreAccDenied = 267, При создании раздела реестра для хранилища лицензий была получена ошибка отказа в доступе.
exDiscReasonRdpEncInvalidCredentials = 768, Обнаружены неверные учетные данные.
exDiscReasonProtocolRangeStart = 4096, Начало диапазона внутренних ошибок протокола. Дополнительные сведения см. В журнале событий сервера.
exDiscReasonProtocolRangeEnd = 32767 Конец диапазона внутренних ошибок протокола.
} ExtendedDisconnectReasonCode;
Скрыть вход добавить макрос {$HIDELOGINS} Administrator
(Win+R) команду eventvwr.msc
- Элемент данных Вход в Windows LSM
Элемент данных
Имя Получаем предыдущее значение для Windows LSM
Тип Zabbix агент
Ключ system.run[«wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I \»Event ID\»|find /n \»2\»|find /v \»1\»»]
Тип информации Числовой (целое положительное)
Интервал обновления 1m
Пользовательские интервалы Переменный
Период хранения истории Storage period 31d
Период хранения динамики изменений Storage period 31d
Отображение значения Как есть
Группы элементов данных LOG-RDP&Local
Описание
Получаем значение, для закрытия триггера на пользователь отключен
Если RDP закрыт, а не завершен то в журнале
24 — отключен
после триггер действие завершение и
23 — выход из сеанса (закрывает триггер)
А если завершен, в логе
23-выход из сеанса
24 — отключен
И по этому триггер на отключение не закрывается
Поэтому смотрим предпоследнюю запись если она 23 триггер не срабатывает.
Активировано V
Предобработка
Шаги предобработки
1 Имя Обрезать Параметры [2] Event ID
2 Имя Обрезать Параметры :
- Вход в Windows RCM
Элемент данных
Имя Вход в Windows Security
Тип Zabbix агент (активный)
Ключ eventlog[«Security»,,,,^(1100|1102|4624|4634|4647)$,,skip]
Тип информации Журнал (лог)
Интервал обновления 15s
Период хранения истории Storage period 31d
Формат времени в журнале (логе) ddMMyyyy:hhmmss
Группы элементов данных LOG-RDP&Local
Описание
1100 — Завершение работы
1102 — Очистка журнала
4624 — Вход в систему для обычной windows Новый вход: — Имя учетной записи: Сведения о сети: — Имя рабочей станции
Тип входа» указан тип выполненного входа. Самыми распространенными являются типы 2 (интерактивный) и 3 (сетевой).
4648 — Вход Windows (серверов) Были использованы учетные данные следующей учетной записи: Имя учетной записи: Целевой сервер: — Имя целевого сервера: (Попытка входа)
(Имя целевого сервера: FS Имя учетной записи: User) Были использованы учетные данные следующей учетной записи:
Имя учетной записи:Admin
4634 — выход (23 в 2 журнале)
4647 — выход
4778 — Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID)
4799 — Отключение от RDP сеанса
9009 — Пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен
(Win+R) команду eventvwr.msc
Активировано
- Элемент данных Вход в Windows Security
Элемент данных
Имя Вход в Windows RCM
Тип Zabbix агент (активный)
Ключ eventlog[«Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational»,,,,^(1149|4624|4625)$,,skip]
Тип информации Журнал (лог)
Интервал обновления 15s
Период хранения истории Storage period 31d
Формат времени в журнале (логе) ddMMyyyy:hhmmss
Группы элементов данных LOG-RDP&Local
Описание
1149 — установление сетевого подключение к серверу от RDP клиента пользователя (не аунтификация)
4624 — успешная аутентификация
4625 — ошибка аутентификации
При входе через терминальную службу RDP — LogonType = 10 или 3.
Если LogonType = 7, значит выполнено переподключение к уже имеющейся RDP сессии.
Account Name — имя пользователя
Workstation Name — имя компьютера
Source Network Address — имя пользователя
TargetLogonID – уникальный идентификатор сессии пользователя
(Win+R) команду eventvwr.msc
Активировано
- Элемент данных Вход в Windows RCM
Элемент данных
Имя ClientName
Тип Zabbix агент (активный)
Ключ 1
Тип информации Текст
Интервал обновления 60s
Период хранения истории Storage period 90d
Группы элементов данных LOG-RDP&Local
Описание
через power shell запрашиваем Get-TSSession -State Active | Format-List ClientName
Активировано
- Элемент данных ClientName
Проверка со стороны сервера
zabbix_get -s 192.168.ххх.ххх -k 1
На стороне заббикс агента в конфигурации прописываем следующее
Конфигурация агента ссылается на скрипт повершела
UserParameter=1, powershell C:\zabbix\Scripts\1.ps1
Содержание скрипта 1.ps1
Get-TSSession -ComputerName Program
или
Get-TSSession
или
Get-TSSession | Format-List ClientName
или
Get-TSSession -State Active | Format-List ClientName
Триггеры 4
- Триггеры Монитор внешнего входа Windows
Триггер
Имя RDP auth {{ITEM.VALUE}.iregsub(«(Пользователь: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(источника: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(Код сеанса: .*)», «\1»)}
Важность Информация
Выражение проблемы {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(21)}=1
Генерация ОК событий Выражение восстановления
Выражение восстановления {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(21)}=0
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание
Fires alarm unless RDP login is administrator
21 — успешный Вход
Пожары сигнализации, если RDP логин администратора
Активировано V
Теги
Trigger tags
Имя {{ITEM.VALUE}.iregsub(«Код сеанса: (.*)», «\1»)} Значение
- Триггер Входа Аунтификации Монитор внешнего входа Windows
Триггер
Имя RDP auth povtor {{ITEM.VALUE}.iregsub(«(Пользователь: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(источника: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(Код сеанса: .*)», «\1»)}
Важность Информация
Выражение проблемы {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(25)}=1
Генерация ОК событий Выражение восстановления
Выражение восстановления {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(25)}=0
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание
Fires alarm unless RDP login is administrator
25 — успешное переподключение
Пожары сигнализации, если RDP логин администратора
Активировано V
Теги
Trigger tags
Имя {{ITEM.VALUE}.iregsub(«Код сеанса: (.*)», «\1»)}
- Триггер Повтора Входа Аунтификации Монитор внешнего входа Windows
Триггер
Имя RDP auth otkl {{ITEM.VALUE}.iregsub(«(Пользователь: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(источника: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(Код сеанса: .*)», «\1»)}
Важность Информация
Выражение проблемы
{Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(24)}=1 and
{Windows external login monitor:system.run[«wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I \»Event ID\»|find /n \»2\»|find /v \»1\»»].last()}<>23 and
{Windows external login monitor:system.run[«wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I \»Event ID\»|find /n \»2\»|find /v \»1\»»].diff(0)}=1
Генерация ОК событий Выражение восстановления
Выражение восстановления {Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(24)}=0 or
{Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25|39|40)$,,skip].logeventid(24)}=1 and
{Windows external login monitor:system.run[«wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I \»Event ID\»|find /n \»2\»|find /v \»1\»»].last()}=23
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание
23 — выход из сеанса (закрывает триггер)
24 — отключен
Срабатывает если последняя запись 24 и предпоследняя не равна 23
не создавалось множество указано diff
Активировано V
Теги
Trigger tags
Имя {{ITEM.VALUE}.iregsub(«Код сеанса: (.*)», «\1»)} Значение
- Триггер Отключен Входа Аунтификации Монитор внешнего входа Windows
Триггер
Имя RDP auth {{ITEM.VALUE}.iregsub(«(Тип входа: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(Имя рабочей станции: .*)», «\1»)}
Важность Информация
Выражение проблемы {Windows external login monitor:eventlog[«Security»,,,,^(1100|1102|4624|4634|4647)$,,skip].logeventid(4624)}=1
Генерация ОК событий Выражение восстановления
Выражение восстановления {Windows external login monitor:eventlog[«Security»,,,,^(1100|1102|4624|4634|4647)$,,skip].logeventid(4624)}=0
Режим генерации событий ПРОБЛЕМА Множественный
ОК событие закрывает Все проблемы
Разрешить закрывать вручную V
Описание
Вход с Имя компьютера подключенного по RDP Лог 4624
Активировано
- Триггер Входа Имя ПК Аунтификации Монитор внешнего входа Windows
Про Инфу в триггер 1.Пользователь который подключился 2.Код Сеанса 3.IP-адресс откуда подключился или локальный вход 4.Имя ПК с которого выполнено подключение
На примере диспетчера задач вкладка пользователи
Windows 10
- RDP-подключение.jpg
Windows 7
- Имя клиента.jpg
Из журнала Microsoft-Windows-TerminalServices-LocalSessionManager/Operational можем получить
Пользователь: источника: Код сеанса:
Локально: 21
Службы удаленных рабочих столов: Успешный вход в систему:
/Пользователь: COMPTV\Медиа
Код сеанса: 1
Адрес сети источника: ЛОКАЛЬНЫЕ
Посети: 21
Службы удаленных рабочих столов: Успешный вход в систему:
/Пользователь: COMPTV\Медиа
Код сеанса: 2
Адрес сети источника: 192.168.175.8
Посети: 25
Службы удаленных рабочих столов: Успешное переподключение сеанса:
Пользователь: COMPTV\Медиа
Код сеанса: 1
Адрес сети источника: 192.168.175.8
По сети: 24
Службы удаленных рабочих столов: Сеанс был отключен:
Пользователь: COMPTV\Медиа
Код сеанса: 1
Адрес сети источника: 192.168.175.8
Локально 23
Службы удаленных рабочих столов: Успешный выход из сеанса:
Пользователь: COMPTV\Медиа
Код сеанса: 1
Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)
Триггер RDP auth Пользователь: Домен\MamzikovAA источника: 192.168.175.8 Код сеанса: 4
21
Службы удаленных рабочих столов: Успешный вход в систему:
/Пользователь: Домен\MamzikovAA
Код сеанса: 4
Адрес сети источника: 192.168.175.8
23
Службы удаленных рабочих столов: Успешный выход из сеанса:
Пользователь: Домен\MamzikovAA
Код сеанса: 4
24
Службы удаленных рабочих столов: Сеанс был отключен:
Пользователь: Домен\MamzikovAA
Код сеанса: 4
Адрес сети источника: 192.168.175.8
25
Службы удаленных рабочих столов: Успешное переподключение сеанса:
Пользователь: Домен\Администратор
Код сеанса: 1
Адрес сети источника: 192.168.175.10
Но Имя ПК с которого выполнено подключение в данном логе нет
оно есть в eventlog[«Security»,,,,^(1100|1102|4624|4634|4647)$,,skip]
Журналы Windows — Безопасность
Вход с Имя компьютера подключенного по RDP Лог 4624
Тип входа: Имя рабочей станции:
Описание Кодов:
1100 — Завершение работы
1102 — Очистка журнала
4624 — Вход в систему для обычной windows Новый вход: — Имя учетной записи: Сведения о сети: — Имя рабочей станции
4648 — Вход Windows (серверов) Были использованы учетные данные следующей учетной записи: Имя учетной записи: Целевой сервер: — Имя целевого сервера: (Попытка входа)
4634 — выход (23 в 2 журнале)
4647 — выход
4778 — Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID)
4799 — Отключение от RDP сеанса
9009 — Пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен
(Win+R) команду eventvwr.msc
4624 — Вход в систему для обычной windows Новый вход: — Имя учетной записи: Сведения о сети: — Имя рабочей станции
Вход с учетной записью выполнен успешно.
Субъект:
ИД безопасности: S-1-5-18
Имя учетной записи: FSServer$
Домен учетной записи: WORKGROUP
Код входа: 0x3e7
Тип входа: 10 не совпадает с кодом сеанса
Новый вход:
ИД безопасности: S-1-5-21-52705171-3967056117-1643963046-500
Имя учетной записи: Администратор
Домен учетной записи: FSServer
Код входа: 0x163d7532
GUID входа: {00000000-0000-0000-0000-000000000000}
Сведения о процессе:
Идентификатор процесса: 0xdf0
Имя процесса: C:\Windows\System32\winlogon.exe
Сведения о сети:
Имя рабочей станции: FSServer
Сетевой адрес источника: 192.168.175.8
Порт источника: 41509
Сведения о проверке подлинности:
Процесс входа: User32
Пакет проверки подлинности: Negotiate
Промежуточные службы: —
Имя пакета (только NTLM): —
Длина ключа: 0
Данное событие возникает при создании сеанса входа. Оно создается в системе, вход в которую выполнен.
Поля «Субъект» указывают на учетную запись локальной системы, запросившую вход. Обычно это служба, например, служба «Сервер», или локальный процесс, такой как Winlogon.exe или Services.exe.
В поле «Тип входа» указан тип выполненного входа. Самыми распространенными являются типы 2 (интерактивный) и 3 (сетевой).
Поля «Новый вход» указывают на учетную запись, для которой создан новый сеанс входа, то есть на учетную запись, с которой выполнен вход.
В полях, которые относятся к сети, указан источник запроса на удаленный вход. Имя рабочей станции доступно не всегда, и в некоторых случаях это поле может оставаться незаполненным.
Поля сведений о проверке подлинности содержат подробные данные о конкретном запросе на вход.
— GUID входа — это уникальный идентификатор, который позволяет сопоставить данное событие с событием KDC.
— В поле «Промежуточные службы» указано, какие промежуточные службы участвовали в данном запросе на вход.
— Поле «Имя пакета» указывает на подпротокол, использованный с протоколами NTLM.
— Поле «Длина ключа» содержит длину созданного ключа сеанса. Это поле может иметь значение «0», если ключ сеанса не запрашивался.
4648 — Вход Windows (серверов) Были использованы учетные данные следующей учетной записи: Имя учетной записи: Целевой сервер: — Имя целевого сервера:
Выполнена попытка входа в систему с явным указанием учетных данных.
Субъект:
ИД безопасности: Домен\Администратор
Имя учетной записи: Администратор
Домен учетной записи: Домен
Код входа: 0x27854ae
GUID входа: {a5064763-d331-b7a3-1f58-df1c9bbdb9e9}
Были использованы учетные данные следующей учетной записи:
Имя учетной записи: back
Домен учетной записи: Домен
GUID входа: {00000000-0000-0000-0000-000000000000}
Целевой сервер:
Имя целевого сервера: nas2
Дополнительные сведения: nas2
Сведения о процессе:
Идентификатор процесса: 0x4
Имя процесса:
Сведения о сети:
Сетевой адрес: —
Порт: —
Данное событие возникает, когда процесс пытается выполнить вход с учетной записью, явно указав ее учетные данные. Это обычно происходит при использовании конфигураций пакетного типа, например, назначенных задач, или выполнении команды RUNAS
4647 — выход
Выход, запрошенный пользователем:
Субъект:
ИД безопасности: S-1-5-21-59707171-3867655147-1643063056-500
Имя учетной записи: Администратор
Домен учетной записи: FSServer
Код входа: 0x163d7532
Данное событие возникает, когда выход начат. Дальнейшие действия, запрошенные пользователем, не выполняются. Данное событие можно рассматривать как событие выхода.
4634 — выход (23 в 2 журнале)
Выполнен выход учетной записи из системы.
Субъект:
ИД безопасности: Домен\MamzikovAA
Имя учетной записи: MamzikovAA
Домен учетной записи: Домен
Код входа: 0x28a9692
Тип входа: 3
Данное событие возникает при уничтожении сеанса входа. Его можно однозначно связать с событием входа с помощью значения «Код входа». Коды входа остаются уникальными после перезагрузки, но они уникальны только на одном компьютере.
- Пример eventlog Security 4624.jpg
Сделать 2 элемента в 1 триггер {ITEM.VALUE} получаем только значение с одного элемента которое первее отработает, второй элемент уже не попадает вариант отпадает. Сделать 2 триггера для того чтобы видеть имя подключившегося ПК как то не целесообразно.
В общем Элемент Вход в Windows Security — Отключен и Триггер так же отключен RDP auth {{ITEM.VALUE}.iregsub(«(Тип входа: .*)», «\1»)} {{ITEM.VALUE}.iregsub(«(Имя рабочей станции: .*)», «\1»)}
Вход в Windows RCM-Remote Connection Manager
- Windows RCM-Remote Connection Manager
1149 — установление сетевого подключение к серверу от RDP клиента пользователя (не аунтификация)
4624 — успешная аутентификация
4625 — ошибка аутентификации
При входе через терминальную службу RDP — LogonType = 10 или 3.
Если LogonType = 7, значит выполнено переподключение к уже имеющейся RDP сессии.
Account Name — имя пользователя
Workstation Name — имя компьютера
Source Network Address — имя пользователя
TargetLogonID – уникальный идентификатор сессии пользователя
(Win+R) команду eventvwr.msc
Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operationa
1149 — установление сетевого подключение к серверу от RDP клиента пользователя (не аунтификация)
Службы удаленных рабочих столов: Успешная проверка подлинности пользователя:
Пользователь: Администратор
Домен: FSServer
Адрес источника сети: 192.168.175.8
Следующая проблемка
Отключенные пользователи которые не завершили сеанс, а просто его закрыли! Корректно нужно завершать сеанс, так же нужно проверять.
Копятся не закрываются триггеры
- Откл копятся.jpg
Разница Завершения Сеанса пользователя и отключения
- Вход и Завершение сеанса RDP.jpg
- Вход и Закрытие RDP на крестик.jpg
Так как
- По завершению и закрытию сеанса RDP
Завершение сеанса
23 — выход из сеанса (закрываем триггер все хорошо или не даем триггеру открыться)
24 — отключен
При закрытии сессии RDP на крестик
24 — отключен сработал триггер (выполним действие на завершение пользователя) и дальше его ничто уже не закроет так как 23 уже было в логе
23 — выход из сеанса, сработало действие на завершение сеанса пользователя по триггеру отключен
Открытие Срабатывание триггера отключённых пользователей происходить по 24 значению лога
а закрытие триггера по 23 значению лога
23 — выход из сеанса (закрывает триггер)
24 — отключен
Срабатывает если последняя запись 24 и предпоследняя не равна 23
не создавалось множество указано diff
По этому пришлось сделать еще один элемент который берет предыдущее значение из лога , уже не раз 15 секунд, а раз в 1 минуту.
Хотелось бы получать все с одного элемента но что делать.
system.run[«wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I \»Event ID\»|find /n \»2\»|find /v \»1\»»]
По отключенным триггер срабатывает если 24 и предыдущая строка не 23
Триггер на отключение срабатывает
С журнала последний код 24 — отключен .logeventid(24)}=1
И
Предыдущее значение не равно 23 выход из сеанса .last()}<>23
И
не создавалось множество указано .diff(0)}=1
Закрытие триггера на отключение
С журнала последнее значение не 24 — отключен .logeventid(24)}=0
Или
С журнала последний код 24 — отключен .logeventid(24)}=1
И
Предпоследнее значение 23 — выход из сеанса .last()}=23
Так же была попытка сделать через теги , корреляцию.
Идея была в чем до функции diff создавалось множество триггеров на отключение с обычного элемента, их надо было закрывать старые или не открывать новые , чтоб они не дублировались. у нас есть значение тега код сеанса например 2 зная имя триггера и код сеанса даем параметр не открывать больше 1 если уже открыт, но тег 2 как только триггер сработал он у нас есть в значении переменной {EVENT.TAGS} но спустя 15 секунд повторного запроса элемента или раз в 1 минуту предыдущего значения элемента , переменная тега {EVENT.TAGS} обнуляется пустая и корреляция не работает, хотя тег сбоку триггера при открытии запоминается и держится пока триггер не закроется.
Теги и регулярное выражение {{ITEM.VALUE}.iregsub(«…….)», «\1»)}
Добрый день! Поясните правильно ли я понимаю работу тегов или нет.
Есть элемент данных для мониторинга пользователей windows на основе лога
eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip]
Запрашиваю каждую 1 минуту
Описание
17 — ошибка Не удалось запустить службу удаленного рабочего стола
21 — успешный Вход
22 — получено уведомление о запуске оболочки
23 — выход из сеанса
24 — отключен
25 — успешное переподключение
Триггер на отключившихся пользователей которые просто закрыли на крестик сессию RDP , а не завершили сеанс.
Проблема
{Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip].logeventid(24)}=1
Восстановление
{Windows external login monitor:eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip].logeventid(24)}=0
В имени тега есть регулярка которая показывает код сеанса данного пользователя {{ITEM.VALUE}.iregsub(«Код сеанса: (.*)», «\1»)}
Суть вопроса в чем
Кто то отключился Сработал триггер, регулярка отработала присвоила триггеру тег например 2
Дальше у меня действие спустя 5 минут завершить сессию данного пользователя (мало ли просто обрыв инет пропал даю 5 минут ожидания)
Элемент за это время у нас еще отпроситься 4 раза, естественно там регулярки не будет, так как изменений в логе нет по этой сессии
Сам же отвечу пустые Логи не приходят, только идут по штампу времени значит значение тега сохраняется, так же если будут изменения лога присвоится другой ID и триггер закроется или сработает другой или действия.
И когда срабатывает действие выполнить команду logoff «{EVENT.TAGS}» /server:{HOST.CONN}
то макрос {EVENT.TAGS} выходит пустой
Сам отвечу не будет пустым, выше ответ почему.
но сбоку сработавшего триггера значение тега есть никуда не пропало выходит что он это значение никак не берет? и его никак не взять?
Т.е. действие нужно выполнять сразу пока элемент повторно не получил пустое значение ?
- tags-vopros0
- tags-vopros1
В некоторых попытках в триггер можно получить предыдущее значение журнала (лога) но уже нельзя сравнить id
Открываем Журнал событий Run (Win+R) команду eventvwr.msc
Откуда можем взять данные:
1. Журналы Windows — Безопасность eventlog[«Security»,,,,^(1100|1102|4624|4648|4634|4647)$,,skip]
1100 — Завершение работы
1102 — Очистка журнала
4624 — Вход в систему для обычной windows Новый вход: — Имя учетной записи: Сведения о сети: — Имя рабочей станции
4648 — Вход Windows (серверов) Были использованы учетные данные следующей учетной записи: Имя учетной записи:
Целевой сервер: — Имя целевого сервера:
4634 — выход (23 в 2 журнале)
4647 — выход
4778 — Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID)
4799 — Отключение от RDP сеанса
9009 — Пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен
2. Microsoft-Windows-TerminalServices-LocalSessionManager/Operational eventlog[«Microsoft-Windows-TerminalServices-LocalSessionManager/Operational»,,,,^(21|23|24|25)$,,skip]
17 — ошибка Не удалось запустить службу удаленного рабочего стола
21 — успешный Вход
22 — полученно уведомление о запуске оболочки
23 — выход из сеанса (закрывает триггер) (4634 в 1 журнале)
24 — отключен
25 — успешное переподключение
39 — (Session <A> has been disconnected by session <B>) – пользователь сам отключился от своей RDP сессии, выбрав соответствующий пункт меню (а не просто закрыл окно RDP клиента).
Если идентификаторы сессий разные, значит пользователя отключил другой пользователь (или администратор).
40 — Здесь нужно смотреть на код причины отключения в событии. Например:
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 в меню.
3. Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operationa eventlog[«Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational»,,,,^(1149|4624|4625)$,,skip]
1149 — установление сетевого подключение к серверу от RDP клиента пользователя (не аунтификация)
4624 — успешная аутентификация
4625 — ошибка аутентификации
При входе через терминальную службу RDP — LogonType = 10 или 3.
Если LogonType = 7, значит выполнено переподключение к уже имеющейся RDP сессии.
Account Name — имя пользователя
Workstation Name — имя компьютера
Source Network Address — имя пользователя
TargetLogonID – уникальный идентификатор сессии пользователя
Об значениях в триггерах как формируются
Регулярное выражение Совпадение значения с регулярным выражением <шаблона> и замена значения в соответствии с <выводом>.
Регулярное выражение поддерживает извлечение до 10 захваченных групп в \N последовательности.
Элемент данных станет неподдерживаемым в случае ошибки при поиске соответствия во входящем значении.
Параметры:
шаблон — регулярное выражение
вывод — шаблон форматирования вывода. \N (где N=1..9) — управляющая последовательность заменяется N-нной совпадающей группой.
Управляющая последовательность \0 заменяется совпадающим текстом
Поддерживается начиная с 3.4.0.
Пожалуйста, обратитесь в разделу регулярных выражений для ознакомления с некоторыми существующими примерами.
{ITEM.LASTVALUE<1-9>}
Последнее значение элемента данных N-го элемента данных в выражении триггера вызвавшего это оповещение.
Поддерживается начиная с 1.4.3. Это алиас для {{HOSTNAME}:{TRIGGER.KEY}.last(0)}
> Оповещения, основанные на триггерах
> Имена триггеров и описания Последнее значение N-го элемента данных из выражения триггера, который вызвал оповещение.
В веб-интерфейсе раскрывается в *НЕИЗВЕСТНО*, если последнее значение истории собрано более чем ZBX_HISTORY_PERIOD секунд назад (задается в defines.inc.php).
Поддерживается начиная с 1.4.3. Является алиасом к {{HOST.HOST}:{ITEM.KEY}.last()}
{ITEM.VALUE<1-9>}
Последнее значение N-го элемента данных в выражении триггера, если используется для отображения триггеров.
Историческое значение (точно когда произошло событие) N-го элемента данных из выражения триггера, если используется для отображения событий и оповещений.
Поддерживается начиная с Zabbix 1.4.3.
{HOSTNAME<1-9>}
Имя узла сети N-го элемента данных из триггера вызвавшего это оповещение.
Поддерживается в оповещениях авторегистрации начиная с версии 1.8.4.
{$MACRO}
Пользовательские макросы. Поддерживается в именах триггеров и в описаниях элементов данных начиная с версии 1.8.4.
Имя клиента из реестра
Есть query session, query user, quser /server 192.168.128.50, query user /server 192.168.128.50, query session /server 192.168.128.50,
query session /server 192.168.128.50 /counter, Qwinsta, tasklist , но они показывают только имя пользователя.
переменная %CLIENTNAME%
echo %CLIENTNAME%
echo %SESSIONNAME%
HKCU\Environment\Clientname
HKEY_CURRENT_USER\Volatile Environment\1 — CLIENTNAME (SESSIONNAME)
HKEY_USERS\S-1-5-21-3002483080-1650114603-3144430796-1000\Volatile Environment\1 — CLIENTNAME
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer, параметр «LOGON USER NAME»
Поставьте, PSTerminalServices (http://psterminalservices.codeplex.com/ … view/65937) и с помощью
Имена пользователей я вырезал. Модуль можно ставить на любой машине с powershell
PS C:\Windows\system32> Get-TSSession -ComputerName TSFarm501
WshShell = Новый COMОбъект(«WScript.Shell»);
WshSysEnv = WshShell.Environment(«Process»);
Сообщить(«Имя компьютера «+WshSysEnv.Item(«CLIENTNAME»));
Работает только в терминальной сессии
%USERPROFILE%\AppData\Local\Temp
%USERPROFILE%\AppData\Local\Temp
для команды для текущего пользователя
reg query «HKCU\Volatile Environment»
Для конкретного пользователя
HKEY_USERS\S-1-5-21-3002483080-1650114603-3144430796-1000\Volatile Environment
реестр всех пользователей
C:\mkdir c:\Temp
Regedit.exe /e c:\temp\yourname.reg
Вычисляемый элемент
last(«eventlog[\»Microsoft-Windows-TerminalServices-LocalSessionManager/Operational\»,,,,^(21|23|24|25|39|40)$,,skip]») не катит поле не числовое
logeventid(«eventlog[\»Microsoft-Windows-TerminalServices-LocalSessionManager/Operational\»,,,,^(21|23|24|25|39|40)$,,skip]»,23) получаем 0 или 1
date
Текущая дата в формате ГГГГММДД. Поддерживаемые типы значений: любые Пример результата: 20150731
time
Текущее время в формате ЧЧММСС. Поддерживаемые типы значений: любые Пример возвращаемого значения: 123055
fuzzytime (сек)
Проверка, на сколько отличается значение элемента данных (как штамп времени) от времени Zabbix сервера. сек — секунды Поддерживаемые типы значений: float, int
Возвращает:
1 — если разница между штампом времени значения элемента данных и штампом времени Zabbix сервера меньше или равна сек секунд
0 — в противном случае.
Обычно используется с system.localtime для проверки, что локальное время синхронизировано с локальным временем Zabbix сервера. Обратите внимание, что элемент данных ‘system.localtime’ должен быть настроен пассивной проверкой.
Также можно использовать с ключом vfs.file.time[/путь/к/файлу,modify] для проверки, что файл не обновлялся длительное время.
Пример: fuzzytime(60)=0 > обнаружение проблемы, если разница во времени больше 60 секунд
Имя Time diff
Тип Вычисляемое
Ключ system.localtime.fuzzytime
Формула fuzzytime(system.localtime,60)
Тип инфы Числовой (целое положительное)
Интервал 1m
Если 3 последних 0 т.е. 0+0+0 = 0 значит триггер срабатывает у нас есть расхождение более чем на 1 минуту
Триггер
system.localtime.fuzzytime.sum(#3)}=0
system.localtime -формат ДД.ММ.ГГГГ ЧЧ:ММ:СС
wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /f:text|FIND /I «Event ID» — от самых старых к новым 2строки
wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I «Event ID» — от новых к старым строкам пример 2строки
wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I «Event ID»|find /n «2»|find /v «1»
/c:<Count> Задает максимальное число событий для чтения.
/rd:<Direction> Указывает направление чтения событий. <Direction>может иметь значение true или false. Если значение равно true, то первыми возвращаются самые последние события.
/f:<Format> Указывает, что выходные данные должны быть в формате XML или текстовый формат. Если <Format> параметр имеет значение XML, выходные данные отображаются в формате XML. Если <Format> является текстом, выходные данные отображаются без XML-тегов. Значение по умолчанию — Text.
FIND /I — Поиск без учета регистра символов «строка» — Искомая строка
FIND /N — Вывод номеров отображаемых строк.
FIND /V — Вывод всех строк, НЕ содержащих заданную строку.
Проверка через заббикс
zabbix_get -s 192.168.ХХХ.ХХХ -p 10050 -k system.run[«wevtutil qe Microsoft-Windows-TerminalServices-LocalSessionManager/Operational /c:2 /rd:true /f:text|FIND /I \»Event ID\»|find /n \»2\»|find /v \»1\»»]
Кото для теста хочет подключатся к учетной записи по RDP без пароля не обходимо выполнить следующее
При попытке подключиться к компьютеру под управлением Windows с помощью средства дистанционного управления рабочим столом появляется следующее сообщение об ошибке: Вход в систему невозможен из-за ограничений для учетной записи.
Подобное поведение наблюдается, если используемая для подключения учетная запись имеет пустой пароль. Невозможно установить подключение к удаленному рабочему столу, используя учетную запись с пустым паролем.
Чтобы устранить эту проблему и подключиться к удаленному рабочему столу, войдите в систему с консоли компьютера и установите пароль для используемой учетной записи.
Такое поведение является особенностью данного продукта
Ограничения, накладываемые пустым паролем, можно отключить, используя политику. Найдите и измените соответствующую политику, выполнив следующие действия:
Нажмите кнопку Пуск, выберите пункт Выполнить (win + R), введите команду gpedit.msc и нажмите кнопку OK, чтобы запустить редактор объектов групповой политики.
Откройте раздел Конфигурация компьютера\Конфигурация Windows\Параметры безопасности\Локальные политики\Параметры безопасности\Учетные записи: Limit local account use of blank passwords to console logon only.
Дважды щелкните элемент Limit local account use of blank passwords to consol logon only.(:ограничить использования пустых паролей только для консолей входа)
Выберите отключен и нажмите кнопку OK.
Закройте редактор групповой политики.
Примечание. По умолчанию данная политика включена.