Log terminal server windows

Tracking and Analyzing Remote Desktop Activity Logs in Windows

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

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

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

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

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

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

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

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

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

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

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

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

Читайте также:  Runtime check failed root ���� ������

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

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

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

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

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

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

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

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

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

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

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

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

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

Error message when you try to log on to a Windows Server 2003-based terminal server: Windows cannot load the user’s profile but has logged you on with the default profile for the system

This article provides a solution to an issue that occurs when you log on to a Windows Server 2003-based terminal server.

Original product version: В Windows Server 2003
Original KB number: В 935649

Symptoms

When you try to log on to a Microsoft Windows Server 2003-based terminal server, you receive the following error message:

Windows cannot load the user’s profile but has logged you on with the default profile for the system.

Detail: Insufficient system resources exist to complete the requested service.

When this problem occurs, the following events are logged in the Application log on the terminal server.

Cause

You experience this problem if many users are logged on to the terminal server.

Resolution

This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:
322756 How to back up and restore the registry in Windows

To resolve this problem, modify the registry to increase the PoolUsageMaximum value and the PagedPoolSize value. To do this, follow these steps:

Читайте также:  Windows 10 подключение телевизора через wifi

Click Start, click Run, type regedit, and then click OK.

Locate and then click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management

On the Edit menu, point to New, and then click DWORD Value.

In the New Value #1 box, type PoolUsageMaximum, and then press ENTER.

Right-click PoolUsageMaximum, and then click Modify.

In the Value data box, type 60, click Decimal, and then click OK.

If the PagedPoolSize registry entry exists, go to step 8. If the PagedPoolSize registry entry does not exist, create it. To do this, follow these steps:

  1. On the Edit menu, point to New, and then click DWORD Value.
  2. In the New Value #1 box, type PagedPoolSize, and then press ENTER.

Right-click PagedPoolSize, and then click Modify.

In the Value data box, type ffffffff, and then click OK.

Exit Registry Editor, and then restart the computer.

More information

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

312362 Server is unable to allocate memory from the system paged pool

Did this fix the problem

Check whether the problem is fixed. If the problem is fixed, you are finished with this section. If the problem is not fixed, you can contact support.

How to Log off all Terminal Server Session Users from a Command Prompt

This article provides some information about how to log off all Terminal Server Session Users from a Command Prompt.

Original product version: В Windows Server 2012 R2
Original KB number: В 259436

Summary

Under some conditions, an administrator may want to force a logoff of all users currently logged on to a Windows NT 4.0 Server, Terminal Server Edition-based computer. You can do so by creating a batch file that calls two Terminal Server specific commands, QUERY, and LOGOFF.

Performing the following procedure logs off all users currently logged onto the Terminal Server. This may result in a loss of unsaved data. Because of this, extreme caution is advised.

More information

To create a batch file that calls these two Terminal Server specific commands, place the following information into a batch (.bat) file:

This batch file may be run at any time the Administrator desires to force the logoff of all users that are not logged on to the Terminal Server console.

Query is a multi-purpose command found within the Terminal Server environment. In this case, Query Session creates a list of all sessions running on the Terminal Server, complete with Session ID numbers. Within the batch file, this output is redirected to a text file. The FOR statement then parses each line of the text file, skipping the first line, and looking for the Session ID number found in the third column. It then places this variable into Logoff, resulting in that session being logged off.

It is not uncommon to receive an error message when you run this batch file. If a user is logged on to the Terminal Server console, the following error message is generated:

Could not logoff session ID 0 from session Console, Error code 5
Error [5]: Access is denied.

It is due to a limitation of the Logoff command. It cannot force the logoff of the console session. A work-around to this issue would be to modify the batch file to read:

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

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

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

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

  1. Network Connection
  2. Authentication
  3. Logon
  4. Session Disconnect/Reconnect
  5. Logoff
Читайте также:  Linux graphics hardware acceleration

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Оцените статью