- How to track users logon/logoff
- Summary
- Option 1
- Option 2
- Interactive logon: Message text for users attempting to log on
- Reference
- Possible values
- Best practices
- Location
- Default values
- Policy management
- Restart requirement
- Security considerations
- Vulnerability
- Countermeasure
- Potential impact
- Получаем логи (историю) входа пользователя в домен AD
- Политика аудита входа пользователя в домен
- PowerShell: истории сетевых входов пользователя в домен
- Получаем информацию об активности пользователя в домене по событиям Kerberos
How to track users logon/logoff
This article describes how to track users logon/logoff.
Original product version: В Windows Server 2003
Original KB number: В 556015
This article was written by Yuval Sinay, Microsoft MVP.
Summary
The following article will help you to track users logon/logoff.
Option 1
Enable Auditing on the domain level by using Group Policy:
Computer Configuration/Windows Settings/Security Settings/Local Policies/Audit Policy
There are two types of auditing that address logging on, they are Audit Logon Events and Audit Account Logon Events.
Audit «logon events» records logons on the PC(s) targeted by the policy and the results appear in the Security Log on that PC(s).
Audit «Account Logon» Events tracks logons to the domain, and the results appear in the Security Log on domain controllers only.
Create a logon script on the required domain/OU/user account with the following content:
Create a logoff script on the required domain/OU/user account with the following content:
Please be aware that unauthorized users can change this scripts, due the requirement that the SHARENAME$ will be writeable by users.
Option 2
Use WMI/ADSI to query each domain controller for logon/logoff events.
Community Solutions Content Disclaimer
MICROSOFT CORPORATION AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY, RELIABILITY, OR ACCURACY OF THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN. ALL SUCH INFORMATION AND RELATED GRAPHICS ARE PROVIDED «AS IS» WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION AND RELATED GRAPHICS, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, TITLE AND NON-INFRINGEMENT. YOU SPECIFICALLY AGREE THAT IN NO EVENT SHALL MICROSOFT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF USE, DATA OR PROFITS, ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OR INABILITY TO USE THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN, WHETHER BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE, EVEN IF MICROSOFT OR ANY OF ITS SUPPLIERS HAS BEEN ADVISED OF THE POSSIBILITY OF DAMAGES.
Interactive logon: Message text for users attempting to log on
Applies to:
Describes the best practices, location, values, management, and security considerations for the Interactive logon: Message text for users attempting to log on security policy setting.
Reference
The Interactive logon: Message text for users attempting to log on and Interactive logon: Message title for users attempting to log on policy settings are closely related.
Interactive logon: Message text for users attempting to log on specifies a text message to be displayed to users when they log on.
Interactive logon: Message title for users attempting to log on specifies a title to appear in the title bar of the window that contains the text message. This text is often used for legal reasons — for example, to warn users about the ramifications of misusing company information, or to warn them that their actions might be audited.
Not using this warning-message policy setting leaves your organization legally vulnerable to trespassers who unlawfully penetrate your network. Legal precedents have established that organizations that display warnings to users who connect to their servers over a network have a higher rate of successfully prosecuting trespassers.
When these policy settings are configured, users will see a dialog box before they can log on to the server console.
Possible values
The possible values for this setting are:
Best practices
It is advisable to set Interactive logon: Message text for users attempting to log on to a value similar to one of the following:
- IT IS AN OFFENSE TO CONTINUE WITHOUT PROPER AUTHORIZATION.
- This system is restricted to authorized users. Individuals who attempt unauthorized access will be prosecuted. If you are unauthorized, terminate access now. Click OK to indicate your acceptance of this information.
Any warning that you display in the title or text should be approved by representatives from your organization’s legal and human resources departments.
Location
Computer Configuration\Windows Settings\Security Settings\Local Policies\Security Options
Default values
The following table lists the actual and effective default values for this policy. Default values are also listed on the policy’s property page.
Server type or GPO | Default value |
---|---|
Default Domain Policy | Not defined |
Default Domain Controller Policy | Not defined |
Stand-Alone Server Default Settings | Not defined |
DC Effective Default Settings | Not defined |
Member Server Effective Default Settings | Not defined |
Client Computer Effective Default Settings | Not defined |
Policy management
This section describes different requirements to help you manage this policy.
Restart requirement
None. Changes to this policy become effective without a device restart when they are saved locally or distributed through Group Policy.
Security considerations
This section describes how an attacker might exploit a feature or its configuration, how to implement the countermeasure, and the possible negative consequences of countermeasure implementation.
There are two policy settings that relate to logon displays:
The first policy setting specifies a text message that displays to users when they log on, and the second policy setting specifies a title for the title bar of the text message window. Many organizations use this text for legal purposes; for example, to warn users about the ramifications of misuse of company information, or to warn them that their actions may be audited.
Vulnerability
Users often do not understand the importance of security practices. However, the display of a warning message before logon may help prevent an attack by warning malicious or uninformed users about the consequences of their misconduct before it happens. It may also help reinforce corporate policies by notifying employees of appropriate policies during the logon process.
Countermeasure
Configure the Interactive logon: Message text for users attempting to log on and Interactive logon: Message title for users attempting to log on settings to an appropriate value for your organization.
Potential impact
Users see a message in a dialog box before they can log on to the server console.
Получаем логи (историю) входа пользователя в домен AD
Есть несколько различных инструментов получения информации о времени логина пользователя в домен. Время последней успешной аутентификации пользователя в домене можно получить из атрибута lastLogon (обновляется только на контроллере домена, на котором выполнена проверка учетных данных пользователя) или lastLogonTimpestamp (реплицируется между DC в домене, но по умолчанию только через 14 дней). Вы можете получить значение этого атрибута пользователя в редакторе атрибутов AD или командлетом Get-ADUser. Однако иногда нужно получить историю активности (входов) пользователя в домене за большой период времени.
Вы можете получить информацию об успешных входах (аутентфикации) пользователя в домене из журналов контроллеров домена. В этой статье мы покажем, как отслеживать историю входов пользователя в домен с помощью PowerShell.. Т.е. можно получить полную историю активности пользователя в домене, время начала работы и компьютеры, с которых работает пользователь.
Политика аудита входа пользователя в домен
Чтобы в журналах контроллеров домена отображалась информация об успешном/неуспешном входе в систему, нужно включить политику аудита событий входа пользователей.
- Запустите редактор доменных GPO – GPMC.msc;
- Откройте настройки Default Domain Policy и перейдите в раздел Computer Configuration -> Policies -> Windows Settings -> Security Settings –> Advanced Audit Policy Configuration -> Audit Policies -> Logon/Logoff;
Audit Policies -> Logon/Logoff» width=»692″ height=»371″ srcset=»https://winitpro.ru/wp-content/uploads/2020/04/advanced-audit-policy-configuration-greater-audit-polic.png 943w, https://winitpro.ru/wp-content/uploads/2020/04/advanced-audit-policy-configuration-greater-audit-polic-300×161.png 300w, https://winitpro.ru/wp-content/uploads/2020/04/advanced-audit-policy-configuration-greater-audit-polic-768×411.png 768w» sizes=»(max-width: 692px) 100vw, 692px»/>
- Включите две политики аудита (Audit Logon и Audit Other Logon/Logoff Events). Чтобы в журналах Security на DC и компьютерах регистрировались как успешные, так и неуспешные политики входа, выберите в настройках политика аудита опции Success и Failure
- Сохраните изменения в GPO и обновите настройки политик на контроллерах домена командой: gpupdate /force (или подождите 90 минут, без учета репликации между DC).
Теперь при входе пользователя на любой компьютер домена Active Directory в журнале контроллера домена, который выполняет аутентификацию пользователя, появляется событие с Event ID 4624 (An account was successfully logged on). В описании этого события указана учетная запись, которая успешно аутентифицировалась (Account name), имя (Workstation name) или IP адрес (Source Network Address) компьютера, с которого выполнен вход.
Также в поле Logon Type указан тип входа в систему. Нас интересуют следующие коды
- Logon Type 10 – Remote Interactive logon – вход через службы RDP, теневое подключение или Remote Assistance (на DC такое событие может быть при входе администратора, или другого пользователя, которому предоставлены права входа на DC) Это событие используется при анализе событий входа пользователей по RDP.
- Logon Type 3 – Network logon сетевой вход (происходит при аутентфикации пользователя на DC, подключения к сетевой папке, принтеру или службе IIS)
Также можно отслеживать событие выдачи билета Kerberos при аутентификации пользователя. Event ID 4768 — A Kerberos authentication ticket (TGT) was requested. Для этого нужно включить аудит событий в политики Account Logon –> Audit Kerberos Authentication Service -> Success и Failure.
В событии 4768 также указана учетная запись пользователя (Account Name или User ID), который получил билет Kerberos (аутентифицировался) и имя (IP адрес) компьютера.
PowerShell: истории сетевых входов пользователя в домен
С помощью командлета PowerShell Get-Eventlog можно получить все события из журнала контроллера домена, отфильтровать их по нужному коду (EventID) и вывести данные о времени, когда пользователь аутентифицировался в домене, и компьютере, с которого выполнен вход. Т.к. в домене может быть несколько контроллеров домена и нужно получить история входов пользователя с каждого из них, нужно воспользоваться командлетом Get-ADDomainController (из модуля AD для Windows PowerShell). Данный командлет позволяет получить список всех DC в домене.
Следующий PowerShell скрипт позволяет получить все события входа пользователя в домен AD со всех контроллеров домена. На выходе вы получаете таблицу с историей входа пользователя и компьютеров, с которых аутентифицировался пользователь.
# имя пользователя, историю входов которого нужно получить
$checkuser=’*ivanov*’
# получаем информацию об истории входов пользователя за последних 2 дня, можете изменить
$startDate = (get-date).AddDays(-2)
$DCs = Get-ADDomainController -Filter *
foreach ($DC in $DCs)<
$logonevents = Get-Eventlog -LogName Security -InstanceID 4624 -after $startDate -ComputerName $dc.HostName
foreach ($event in $logonevents)<
if (($event.ReplacementStrings[5] -notlike ‘*$’) -and ($event.ReplacementStrings[5] -like $checkuser)) <
# Remote (Logon Type 10)
if ($event.ReplacementStrings[8] -eq 10)<
write-host «Type 10: Remote Logon`tDate: «$event.TimeGenerated «`tStatus: Success`tUser: «$event.ReplacementStrings[5] «`tWorkstation: «$event.ReplacementStrings[11] «`tIP Address: «$event.ReplacementStrings[18] «`tDC Name: » $dc.Name
>
# Network(Logon Type 3)
if ($event.ReplacementStrings[8] -eq 3)<
write-host «Type 3: Network Logon`tDate: «$event.TimeGenerated «`tStatus: Success`tUser: «$event.ReplacementStrings[5] «`tWorkstation: «$event.ReplacementStrings[11] «`tIP Address: «$event.ReplacementStrings[18] «`tDC Name: » $dc.Name
>
>
>
>
Получаем информацию об активности пользователя в домене по событиям Kerberos
Также вы можете получить историю аутентификации пользователя в домене по по событию выдачи билета Kerberos (TGT Request — EventID 4768). В этом случае в итоговых данных будет содержаться меньшее количество событий (исключены сетевые входы, обращения к папкам на DC во время получения политик и выполнения логон-скриптов). Следующий PowerShell скрипт выведет информацию о всех входах пользователей за последние 24 часа:
$alluserhistory = @()
$startDate = (get-date).AddDays(-2)
$DCs = Get-ADDomainController -Filter *
foreach ($DC in $DCs)<
$logonevents = Get-Eventlog -LogName Security -InstanceID 4768 -after $startDate -ComputerName $dc.HostName
foreach ($event in $logonevents)<
if ($event.ReplacementStrings[0] -notlike ‘*$’) <
$userhistory = New-Object PSObject -Property @<
UserName = $event.ReplacementStrings[0]
IPAddress = $event.ReplacementStrings[9]
Date = $event.TimeGenerated
DC = $dc.Name
>
$alluserhistory += $userhistory
>
>
>
$alluserhistory
Обратите, что в этом случае вы не увидите события входов пользователей, которые аутентифицировались с клиентов или приложений, которые используют NTLM вместо Kerberos.