Ntlm windows server 2019

NTLM (NT LAN Manager) – это старый протокол аутентификации Microsoft, который появился еще в Windows NT. Несмотря на то, что еще в Windows 2000 Майкрософт внедрила более безопасный протокол аутентификации Kerberos, NTLM (в основном это NTLMv2) широко используется для аутентификации в Windows сетях до сих пор. В этом статье мы рассмотрим, как отключить протоколы NTLMv1 и NTLMv2, и переключиться на Kerberos в домене Active Directory.

Содержание:

  • Аудит событий NTLM аутентификации в домене
  • Переключаемся на использование аутентфикации NTLMv2
  • Полное отключение NTLM и перевод аутентфикации на Kerberos в домене Active Directory

Основные проблемы NTLMv1 – слабое шифрование, хранение хэша пароля в оперативной памяти в службе LSA (можно извлечь пароли из памяти Windows в открытом виде с помощью утилит типа mimikatz и использовать хэш для дальнейших атак с помощью сценариев Pass-The-Hash), отсутствие взаимной проверки подлинности клиента и сервера, что делает вполне реальными атаки перехвата данных и неавторизованного доступа к ресурсам сети (утилиты типа Responder могут перехватывать данные NTLM, передаваемые по сети и использовать их для доступа к сетевым ресурсам) и ряд других уязвимостей.

Часть этих недостатков исправлена в более новой версии NTLMv2, который использует более криптостойкие алгоритмы шифрования и позволяет предотвратить популярные атаки на NTLM. Начиная с Windows 7 / Windows Server 2008 R2 протоколы аутентфикации NTLMv1 и LM по умолчанию отключены.

Аудит событий NTLM аутентификации в домене

Перед полным отключением NTLM в домене и полном переходе на Kerberos желательно убедиться, что в домене не осталось приложений, которые используют NTLM аутентификацию. В вашей сети могут быть устаревшие устройства или службы, которые все еще используют аутентификацию NTLMv1 вместо NTLMv2 (или Kerberos).

Для отслеживания учетных записей и приложение, которые используют NTLM аутентификацию, вы можете включить политики аудита на всех компьютерах с помощью GPO. Откройте Default Domain Controller Policy, перейдите в раздел Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Security Options найдите и включите политику Network Security: Restrict NTLM: Audit NTLM authentication in this domain, установив ее значение на Enable all.

аудит NTLM аутентификации Network Security: Restrict NTLM: Audit NTLM authentication in this domain

Аналогичным образом включите следующие политики в Default Domain Policy:

  • Network Security: Restrict NTLM: Audit Incoming NTLM Traffic – задайте значение Enable auditing for domain accounts
  • Network security: Restrict NTLM: Outgoing NTLM traffic to remote servers: задайте Audit all

Network Security: Restrict NTLM: Audit Incoming NTLM Traffic

После включения данных политик события использования NTLM аутентификации записываться в журнал событий Event Viewer в секцию Application and Services Logs-> Microsoft -> Windows -> NTLM -> Operation.

Можно проанализировать события на каждом сервере, или собрать все события в центральный Event Log.

Вам нужно собрать события от Microsoft-Windows-Security-Auditing c Event ID 4624 – An Account was successfully logged on. Обратите внимание на информацию в секции “Detailed Authentication Information”. Если в строке Authentication Package указано NTLM, значит для аутентификации этого пользователя использовался протокол NTLM.

Также, если для аутентификации используется NTLM вместо Kerberos, в журнале появится событие Event ID 4776:

The computer attempted to validate the credentials for an account
Authentication Package: MICROSOFT_AUTHENTICATION_PACKAGE_V1_0

Теперь обратите внимание на значение Package Name (NTLM only). Здесь должно быть указано какой протокол (LM, NTLMv1 или NTLMv2) использовался для аутентификации. Таким образом вам нужно идентифицировать все сервера/приложения, которые используют устаревший протокол.

Event ID 4624 – An Account was successfully logged on

Например, для поиска всех событий аутентификации по NTLMv1 по всем контроллерам домена можно использовать такой PowerShell скрипт:

$ADDCs = Get-ADDomainController -filter * -Server dc01.winitpro.ru
$Now = Get-Date
$Yesterday = $Now.AddDays(-1)
$NewOutputFile = "c:\ps\Events\$($Yesterday.ToString('yyyyMMdd'))_AD_NTLMv1_events.log"
function GetEvents($DC){
Write-Host "Searching log on " $DC.HostName
$Events = Get-EventLog "Security" -After $Yesterday.Date -Before $Now.Date -ComputerName $DC.HostName -Message "*NTLM V1*" -instanceid 4624
foreach($Event in $Events){
Write-Host $DC.HostName $Event.EventID $Event.TimeGenerated
Out-File -FilePath $NewOutputFile -InputObject "$($Event.EventID), $($Event.MachineName), $($Event.TimeGenerated), $($Event.ReplacementStrings),($Event.message)" -Append
}

}
foreach($DC in $ADDCs){GetEvents($DC)}

После того, как вы идентифицировали пользователей и приложения, использующие NTLM в вашем домене, попробуйте перевести их на использование Kerberos (возможно с использованием SPN). Некоторые приложения достаточно донастроить для использования Kerberos (см. статьи Kerberos авторизация в IIS, использование Kerberos авторизация в браузерах, использования keytab файла Kerberos для аутентификации в AD). Из личного опыта: некоторые действительно большие коммерческие продукты до сих пор используют проверку подлинности NTLM и не поддерживают Kerberos, некоторые продукты требуют обновления или изменений конфигурации.

Потенциально проблемы при отключении NTLMv1 могут быть у небольших опенсорсных продуктов, различных старых моделей сетевых сканеров (который складывают сканы в сетевые папки), некоторых NAS устройств и другого устаревшего оборудования, ПО и ОС.

Те приложений, которые нельзя переключить на использование NTLM можно добавить в исключения, разрешив им использовать NTLM аутентификацию, даже если она отключена на уровне домена. Для этого используется политика Network security: Restrict NTLM: Add server exceptions for NTLM authentication in this domain. В список исключений нужно добавить имена серверов (NetBIOS имена, IP адреса или FQDN), для аутентификации на которых можно использовать NTLM (конечно, в идеале этот список исключений должен быть пустым). Можно использовать знак подстановки
*
.

Network security: Restrict NTLM: Add server exceptions for NTLM authentication in this domain

Для использования Kerberos аутентификации в приложении нужно указывать DNS имя сервера, а не IP адрес. Если вы указываете IP адрес при подключении к ресурсу, используется NTLM аутентификация.

Переключаемся на использование аутентфикации NTLMv2

Прежде чем полностью отказаться от NTLM в домене AD, сначала рекомендуется отключить его более уязвимая версия NTLMv1. Администратору домена нужно убедиться, что в его сети запрещено использовать NTLM или LM для авторизации, т.к. в некоторых случаях атакующий может с помощью специальных запросов получить ответ на NTLM/LM запрос.

Тип аутентификации можно задать с помощью доменной политики. Откройте консоль управления доменными политиками GPMC.msc и отредактируйте Default Domain Controllers Policy. Перейдите в раздел Computer Configurations -> Policies -> Windows Settings -> Security Settings -> Local Policies -> Security Options и найдите политику Network Security: LAN Manager authentication level (Сетевая безопасность: уровень проверки подлинности LAN Manager).

групповая политика Network Security: LAN Manager authentication level (Сетевая безопасность: уровень проверки подлинности LAN Manager).

В настройках политики есть 6 опций:

  • Send LM & NTLM responses;
  • Send LM & NTLM responses – use NTLMv2 session security if negotiated;
  • Send NTLM response only;
  • Send NTLMv2 response only;
  • Send NTLMv2 response only. Refuse LM;
  • Send NTLMv2 response only. Refuse LM& NTLM.

Политики использования NTLM аутентификации расположены в порядке возрастания их безопасности. По умолчанию в Windows 7 и выше используется настройка Send NTLMv2 response only (Отправлять только NTLMv2-ответ). При этой настройке клиентские компьютеры используют NTLMv2 аутентификацию, но контролеры домены принимают LM, NTLM, и NTLMv2 запросы.

NTLMv2 может использоваться, если не сработал протокол Kerberos и при некоторых операциях (например, при управлении локальными учетными записями и группами на доменных компьютерах), или в рабочих группах.

Вы можете изменить значение политики на более безопасную 6 опцию — “Send NTLMv2 response only. Refuse LM & NTLM”. При этой политике контролеры домена также будут отвергать запросы LM и NTLM.

Также вы можете отключить NTLMv1 через реестр. Для этого в ветке HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa нужно создать параметр DWORD с именем LmCompatibilityLevel и значением от 0 до 5. Значение 5 соответствует значению политики «Отправлять только NTLMv2-ответ. Отказывать LM и NTLM».

В этом же разделе GPO убедитесь, что у вас включена политика Network security: Do mot store Lan Manager hash value on next password change (Сетевая безопасность: не хранить хэш-значения LAN Manager при следующей смене пароля). Эта политика включена по умолчанию, начиная с Windows Vista / Windows Server 2008 и запрещает создание LM-хэша.

Network security: Do mot store Lan Manager hash value on next password change

Если вы убедились, что ваш домен и службы корректно работают без NTLMv1, вы можете пойти дальше и попытаться отказаться от NTLMv2. NTLMv2 хотя и более защищенный протокол аутентификации, но все равно существенно проигрывает Kerberos в плане безопасности (хотя уязвимостей в NTLMv2 намного меньше, чем в первой версии протокола, все-таки существуют возможности перехвата и повторного использования данных, и отсутствует взаимная mutual аутентификации).

Главная риск отключения NTLM – возможное использование в домене устаревших или некорректно настроенных приложений, которые все еще могут использовать проверку подлинности NTLM, и для перехода на Kerberos их придется обновлять или настраивать особым образом.

Если у вас в сети развернут сервер Remote Desktop Gateway, нужно внести дополнительную настройку, которая будет блокировать подключение клиентов с помощью NTLMv1. Создайте в реестре параметр:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\TerminalServerGateway\Config\Core
Type: REG_DWORD
Name: EnforceChannelBinding
Value: 1 (Decimal)

Полное отключение NTLM и перевод аутентфикации на Kerberos в домене Active Directory

Чтобы проверить, как будет работать аутентификация в различных приложениях в домене без использования NTLM, вы можете добавить учетные записи необходимых пользователей в доменную группу Protected Users (группа доступна, начиная с Windows Server 2012 R2), членам которой можно аутентифицироваться только по протоколу Kerberos (нельзя использовать NTLM, Digest Authentication или CredSSP). Так вы можете проверить корректность Kerberos аутентификации пользователя в различных приложениях.

Теперь вы можете полностью отключить NTLM в домене с помощью групповой политики Network Security: Restrict NTLM: NTLM authentication in this domain.

В этой политике доступно 5 опций:

  • Disable: политика отключена (NTLM аутентификация в домене разрешена);
  • Deny for domain accounts to domain servers: контролеры домена запрещают попытки аутентификации NTLM для всех серверов под доменными аккаунтами, возвращается ошибка «NTLM заблокирован»;
  • Deny for domain accounts: контролеры домена запрещают попытки NTLM аутентификации для всех учетных записей домена, возвращается ошибка «NTLM заблокирован»;
  • Deny for domain servers: запрещены запросы NTLM аутентификации для всех серверов;
  • Deny all: контроллеры домена блокируют все запросы NTLM для всех серверов и учетных записей.

Параметр групповой политики - отключить ntlm в active directory

Несмотря на то, что NTLM в домене теперь отключен, он все еще используется для обработки локальных входов на компьютеры (для входов локальных пользователей всегда используется NTLM).

Также с помощью отдельных параметров Default Domain Policy вы можете запретить входящий и исходящий NTLM трафик на компьютерах домена:

  • Network security: Restrict NTLM: Incoming NTLM traffic =
    Deny all accounts
  • Network security: Restrict NTLM: Outgoing NTLM traffic to remote servers =
    Deny all

После включения аудита, при использовании NTLM для аутентификации в Event Viewer также будет появляться событие EventID 6038 от LsaSRV с предупреждением:

Microsoft Windows Server обнаружил, что в настоящее время между клиентами и этим сервером используется проверка подлинности ntlm. это событие возникает один раз при каждой загрузке, когда клиент первый раз использует ntlm с этим сервером.
Microsoft Windows Server has detected that NTLM authentication is presently being used between clients and this server. This event occurs once per boot of the server on the first time a client uses NTLM with this server.
NTLM is a weaker authentication mechanism. Please check:
Which applications are using NTLM authentication?
Are there configuration issues preventing the use of stronger authentication such as Kerberos authentication?
If NTLM must be supported, is Extended Protection configured?

событие ntlm аутентфикации от lsasrv eventid 6038

Вы можете проверить, что для аутентификации пользователя используется Kerberos с помощью команды:

klist sessions

klist sessions вывести все сессии и протоколы аутентфикации (kerberos/ntlm)

Данная команда показывает, что для аутентификации всех пользователей используется Kerberos (кроме встроенного локального пользователя Administrator, для которого всегда используется NTLM).

Если после отключения NTLM вы столкнетесь с частыми событиями блокировки учетных записей пользователей, внимательно изучите события с EventID 4771 (
Kerberos pre-authentication failed
). Смотрите Failure Code в описании ошибки. Там будет указана причина и источник блокировки.

Для дальнейшего эшелонирования защиты в AD рекомендую познакомиться со статьями:

  • Защита от извлечения пароля из памяти утилитами а-ля mimikatz
  • Защита учетных записей администраторов
  • Отключение LLMNR и NetBIOS over TCP/IP

Did you know that Windows has had a built-in capability to function as a SIEM (Security Information and Event Management) system for years, provided you stay within the Windows ecosystem? This powerful feature, known as Windows Event Forwarding (WEF), allows you to centralize event logs from multiple Windows machines, giving you a comprehensive view of your network’s activities.

Today, we’re going to delve into how to use and set up Windows Event Forwarding to get an inventory going on NTLM v1 traffic. By configuring WEF, you can monitor and analyze all kinds if events, helping you detect and address potential security issues in real-time.

Introduction

Windows Event Forwarding (WEF) is a built-in feature available in Microsoft Windows operating systems designed to help organizations manage and analyze event logs in a structured and efficient manner. With WEF, system administrators can centralize event logs from multiple Windows computers and forward them to a central server, providing a consolidated overview of what is happening on those computers.

This functionality is particularly valuable for security and monitoring purposes because it allows organizations to track events in real-time, detect suspicious activities, and quickly identify security incidents. By using WEF, organizations can also reduce the amount of data traffic needed to retrieve event logs from multiple sources, thereby decreasing network load and improving efficiency.

This guide will show the steps on how Windows Event Forwarding should be configured, managed, and used to gain insights from the event logs of Windows computers connected to a domain, with a specific focus on the inventory of NTLMv1. Understanding and correctly implementing WEF can be an important step in improving the security and management of any IT infrastructure.

Architecture overview

The architecture for Windows Event Forwarding (WEF) in this document is based on a domain network where various components play critical roles in effectively managing and analyzing event log data.

  1. Domain Controllers: Domain controllers play a crucial role in handling authentication and enforcing configuration settings on all computers and devices within the domain. They ensure that event logs are correctly generated and logged by the endpoints.
  2. Log collectors: Log collectors are responsible for gathering event log data from endpoints, both clients, and servers, within the domain. These log collectors act as central storage points for log data, enabling consolidated analysis and monitoring.
  3. Endpoints (clients and servers): All machines within the domain are configured to forward event log data to the log collectors. These endpoints are essential for capturing relevant events and forwarding them to the central collection points.

It is important to note that machines outside the domain network are out of the scope of this blog, I’ll write about that feature in the near future. External machines perform their authentication against the domain controllers and servers within the domain where events are captured and logged. For the inventory of NTLMv1 authentication, there is less emphasis on these external machines since most relevant authentication events occur within the internal domain network and can be intercepted accordingly.

Requirements

Before Windows Event Forwarding (WEF) can be used, certain requirements must be met. These ensure smooth implementation without limitations.

  1. Windows version and edition: Ensure that both the source computers and the destination computer where you want to centralize event logs are running Windows operating systems that support WEF. WEF is available in Windows Vista and later versions, including Windows Server operating systems. It is recommended to use the latest version of Windows Server (Windows Server 2019+).
  2. Network connectivity: Ensure that all involved computers can communicate within the network. Necessary firewall rules must be configured to ensure that event logs can be safely forwarded to the central server. Using secure communication with Kerberos is strongly recommended to ensure the confidentiality and integrity of log data. Network traffic uses WSMAN port 5985.
  3. Rights and permissions: To set up and manage WEF, you need administrative rights on both the source computers and the target server. No domain admin rights are needed other than configuring the group policy objects.
  4. Log source configuration: Carefully configure the event logs on the source computers. You need to determine which events you want to collect and forward to the central server. This includes enabling the correct log channels and filtering events based on their relevance to your monitoring and security purposes.

Hardware requirements

The hardware requirements for a single log collector can vary depending on several factors, such as the volume of log data you want to collect, the frequency of events, and the complexity of your analysis needs. Generally, the more data you collect and analyze, the more powerful the hardware needs to be. Here are some general recommendations for the hardware requirements of a log collector:

  1. Processor (CPU): A multi-core processor with good processing speed is important for efficiently processing event logs. The exact requirements vary, but a modern quad-core processor or better is recommended. The processor should have a minimum of 4 cores.
  2. Memory (RAM): The amount of RAM depends on the volume of log data and the complexity of your analyses. Generally, at least 16 GB of RAM is recommended.
  3. Storage: Sufficient storage space is needed to store log data before it is forwarded to a central location. The required storage space depends heavily on the amount of data you collect and how long you want to retain it. Due to the high level of I/O used for writing the data, a fast and reliable storage solution, such as an SSD, is recommended for optimal performance. A minimum storage disk of 80GB is also recommended for the OS Disk.
  4. Network Interface: A fast network connection is essential, especially if you are collecting log data from multiple sources. A gigabit Ethernet connection is minimally recommended.

Collector requirements

The log collector has the capacity to receive data from a maximum of 4000 clients. This means that up to 4000 Windows computers or devices can forward their event logs to this collector for further analysis and storage. It is important to keep this maximum number in mind when planning the implementation to ensure it meets the needs of your organization. If you plan to collect data from more than 4000 clients, consider deploying multiple collectors to distribute the load and maintain optimal performance.

Performance updates

For users of Windows Server 2016 and Windows Server 2019, specific updates are available that offer performance improvements for the use of Windows Event Forwarding (WEF). These updates, KB4537806 for Windows Server 2016 and KB4537818 for Windows Server 2019, are designed to enhance the overall performance and efficiency of WEF.

It is important to note that these updates are typically installed as part of regular Windows updates, provided optional updates are enabled. Given that they can offer significant improvements for WEF implementations, they are highly recommended for organizations deploying WEF to collect and manage event logs.

  • Windows Server 2016: KB4537806
  • Windows Server 2019: KB4537818

Windows event collector setup

The Windows Event Collector (WEC) is a crucial component for the centralized inventory of event logs. It acts as the central collection point for event logs within the domain network and is responsible for receiving and storing log data from endpoints such as clients and servers. Here are the steps to configure it.

Windows Remote Management (WinRM – WSMAN)

Windows Remote Management (WinRM) is a Microsoft service that enables remote communication and management of Windows systems over a network. It allows administrators to execute commands, change configurations, and retrieve data from remote computers running Windows operating systems. With WinRM, administrators can manage system resources and retrieve data from multiple Windows machines without physically accessing each individual computer, which is useful for tasks such as configuration management, troubleshooting, and automation. WinRM is an essential component in using WEF. The following actions are necessary on the WEF collectors.

Note! Windows Server 2008R2 and higher have WinRM enabled by default. The steps below are necessary to ensure this configuration.

WinRM listener

Command-line:

winrm enumerate winrm/config/listener

Expected output:

To view the complete configuration, use the command-line:

Windows firewall

Run the following command-line in an elevated PowerShell console:

Get-NetFirewallRule | Where-Object {$_.Displayname -Like "Windows Remote Management (HTTP-In)" -and $_.Profile -like "*Domain*"} | Select Enabled

Expected output:

Windows Remote Management service

Run the following command-line in an elevated PowerShell console:

Get-Service -Name WINRM | select StartType

Expected output:

Corrective action

If any of the above measures do not produce the desired effect, the following cmdlet can be executed to configure the log collector for using Windows Remote Management:

WinRM collector adjustments for Server 2016/2019

On the collector, both the Windows Event Collector service (WecSvc) and the Windows Remote Management service (WinRM) use certain URLs. However, the default access control lists (ACLs) for these URLs only allow access for the svchost process that runs WinRM. In the default configuration of Windows Server 2016, both WinRM and WecSvc run in a single svchost process. Because this process has access, both services function correctly. However, if you change the configuration so that the services run in separate host processes, WecSvc no longer has access, and event forwarding stops working.

The services function differently in Windows Server 2019. If a Windows Server 2019 computer has more than 3,5 GB of RAM, WinRM and WecSvc run in separate svchost processes by default. Due to this change, event forwarding may also not work correctly in the default configuration.

To correct this oversight, run the following commands in an elevated command console:

netsh http delete urlacl url=http://+:5985/wsman/
netsh http add urlacl url=http://+:5985/wsman/ sddl=D:(A;;GX;;;S-1-5-80-569256582-2953403351-2909559716-1301513147-412116970)(A;;GX;;;S-1-5-80-4059739203-877974739-1245631912-527174227-2996563517)
netsh http delete urlacl url=https://+:5986/wsman/
netsh http add urlacl url=https://+:5986/wsman/ sddl=D:(A;;GX;;;S-1-5-80-569256582-2953403351-2909559716-1301513147-412116970)(A;;GX;;;S-1-5-80-4059739203-877974739-1245631912-527174227-2996563517)

Note! When you have upgraded to Server 2022 from 2016 or 2019 you should also take the steps described here.

Note! This correction does not apply to a new installation of Windows Server 2022.

Restart the server or service after making the changes. To view the current configuration, use the command-line:

Source: https://learn.microsoft.com/en-us/troubleshoot/windows-server/admin-development/events-not-forwarded-by-windows-server-collector

Setting up a Windows Event Forwarding (WEF) subscription

A WEF subscription is used to collect specific events from source computers within the domain and forward them to the Windows Event Collector (WEC) for centralized storage and analysis. Here are the steps to set up a WEF subscription:

On the log collector server, open the event viewer and navigate to “Subscriptions”. Click “Yes” when you receive the following prompt.

Right-click on “Subscriptions” and select “Create Subscription”.

In the dialog box, give the subscription a name and select: “Source computer initiated” then click on “Select Computer Groups…”.

Click on “Add Domain Computers” and add the computer group that needs to forward events. It is advisable to select “Domain Computers” here. Machines will then have the ability to forward events but will need further configuration.

Note! When targeting Domain Controllers, select the group “Domain Controllers” as these are not a part of “Domain Computers”.

Click “OK” in this dialog box. Click “Advanced” at the bottom of the screen and select the option “Minimize Latency”. Click “OK”. These options are available:

  • “Normal” pull delivery every 15 minutes.
  • “Minimize Bandwidth” push delivery every 6 hours.
  • “Minimize Latency” for critical events push delivery every 30 seconds.

Note! The “HTTP” protocol is secured by Kerberos encryption.

In the “Select Events” dialog box, specify the event configuration. This can be done in the UI section or via an XPATH (XML tab). Since detecting NTLMv1 is outside the scope of the UI, the following configuration via an XPath filter is recommended:

<QueryList>  
  <Query Id="0" Path="Security">    
    <Select Path="Security">*[System[(EventID=4624)]] and Event[EventData[Data[@Name='LmPackageName'] and (Data='NTLM V1' or Data='LM')]] </Select>    
    <Suppress Path="Security">*[EventData[Data[@Name='TargetUserName'] and (Data='ANONYMOUS LOGON')]]</Suppress>  
  </Query>
</QueryList>

Note! When Windows does not detect NTLMv2 authentication, it assumes NTLMv1 is being used even when an “Anonymous Logon” occurs. This can create the impression that NTLMv1 authentication is taking place despite enforced policies. To filter this out, the “Suppress” option is added as shown above. For more information, see Microsoft’s documentation.

Click “OK” twice to return to the subscription. It will now be configured according to the set conditions. The following will be representative of this setup.

Event log size

Adjusting the size of the “Forwarded Events” log is important to ensure there is enough space to store log data. Here’s the command-line to set the event log size to 1 gigabyte:

wevtutil sl forwardedevents /ms:1000000000

Log archiving

Log archiving is an important part of event log management. When an event log is full and can no longer contain data, archiving can be enabled to store older events before new data is recorded. This ensures important log data is preserved for further analysis even when the log is full. Enabling this feature ensures no valuable data is lost. Here is the command-line to enable archiving:

wevtutil sl forwardedevents /ab:true /rt:true

WEF configuration via a Group Policy object (GPO)

A Group Policy Object (GPO) is the way to manage the Windows Event Forwarding (WEF) configuration on multiple computers within the domain. Here are the steps to create a WEF configuration via a GPO:

In “Group Policy Management,” create a group policy object in the organizational unit where the machines that need to receive the WEF configuration are located. This GPO can be filtered based on computer names or a specific group.

Note! Assigning a group to a computer object requires a reboot of the respective host.
Hint! This policy exclusively uses computer configuration, therefore set the GPO Status to: “User configuration settings disabled.”

In the policy, navigate to:
Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Restricted Groups

Add a group named “Event Log Readers” and click “OK”.

In “Member of this group,” click “Add” and add the pseudo group “NT AUTHORITY\Network Service.” Click “OK” twice to return.

Note! The above must be done to give the “Network Service” rights to read and forward event logs to the collector.

In the policy, navigate to:
Computer Configuration -> Policies -> Windows Settings -> Security Settings -> System Services

Configure the “Windows Remote Management” service to start automatically. Click “OK” to return.

In the policy, navigate to:
Computer Configuration -> Policies -> Administrative Templates -> Windows Components -> Event Forwarding

Set the following policies:

  • Configure forwarder resource usage: Enabled
    • The maximum forwarding rate: 500
  • Configure target Subscription Manager: Enabled
Server=http://<FQDN of the collector>:5985/wsman/SubscriptionManager/WEC,Refresh=120

Note! The maximum forwarding rate indicates how many log entries a host can forward at a time. A typical deployment will be between 500 and 1000 entries.

Note! The specified refresh interval is for retrieving the WEF configuration from the subscription. When there are few or no changes, this value can be increased.

In the policy, navigate to:
Computer Configuration -> Policies -> Administrative Templates -> Windows Components -> Event Log Service -> Security

Set the following policy:

  • Configure Log Access: Enabled
    • Log Access:
O:BAG:SYD:(A;;0xf0005;;;SY)(A;;0x5;;;BA)(A;;0x1;;;S-1-5-32-573)(A;;0x1;;;S-1-5-20)

Note! In many blogs, S-1-5-20 is replaced by “NS”. This does not work on a Domain Controller; hence, the SID is used in this rule.

Checking the WEF configuration

Once the previously shown configuration is successfully implemented, the log collector configured, and the policies applied to the hosts that need to forward the event log, the endpoints will eventually check in with the log collector.

On the log collector, open the Event Viewer – Subscriptions. The number of “Source Computers” will increase over time.

Right-click and select “Runtime Status” to observe the individual endpoints.

Generating a control event

To test and verify the functionality of Windows Event Forwarding (WEF) and ensure that events are correctly forwarded to the ‘Forwarded Events’ logs, you can execute the following PowerShell command on one of the hosts within the domain:

Write-EventLog -LogName System -EventId 4624 -EntryType Information -Source "System" -Message "This is an event generated for WEF testing purposes"

Note! This event uses the “System” event log instead of “Security”. Access to the security log is restricted and cannot be easily written. To test the above, an additional subscription is needed with the System event log selected.

Open the Event Viewer –> Forwarded Events to check for the generated test event.

Auditing and Group Policy requirements for NTLMv1 logging

To properly capture and log NTLMv1 events, advanced auditing must be enabled, and the correct Group Policy settings must be configured on the relevant Windows computers within the domain. Here are the requirements and steps:

Advanced auditing

Advanced auditing is a feature in Windows operating systems that allows detailed logging of specific events and actions on a computer. It provides more in-depth and accurate information than standard logging, enabling administrators and security professionals to gain detailed insights into system behavior and identify potential security issues.

The default configuration already activates the relevant settings. However, it is advisable to perform a preliminary check to ensure the desired auditing is present. Execute the following command-line:

auditpol.exe /get /category:Logon/Logoff

Note! Logon must have at least success enabled to generate the desired events.
NTLM Auditing in Group Policy

Ensure that the GPO with the configured audit policy settings is applied to the target computers. Link the GPO to the relevant organizational unit (OU).

In the policy, navigate to:

Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Local Policies -> Security Options

  • (All domain members, incl DCs):
    Network Security: Restrict NTLM: Audit Incoming NTLM Traffic:
    Enable auditing for domain accounts.
  • (All domain members, incl DCs):
    Network Security: Restrict NTLM: Outgoing NTLM traffic to remote servers: Audit All.
  • (Domain Controllers only):
    Network Security: Restrict NTLM: Audit NTLM authentication in this domain: Enable all.

Forcing NTLMv1 for testing purposes

Forcing NTLMv1 authentication within a managed domain requires specific steps and considerations to ensure it is done safely. This chapter focuses on the procedure and considerations for enabling NTLMv1 authentication for testing purposes within a Windows environment. The following steps are discussed to effectively manage this process.

Domain Controller

In a policy on the organizational unit for domain controllers, the group policy setting “Network security: LAN manager authentication level” should not be set to or should not have the maximum value of 5 “Send NTLMv2 response only/refuse LM”, any other setting is fine for testing.

Server class devices

Server class devices do not require changes as long as domain accounts are used for testing.

EndPoint devices

A Windows EndPoint device must have the value “Send LM & NTLM responses” in the group policy setting “Network security: LAN manager authentication level”.

A reboot is not strictly necessary.

Authentication test

From the Windows EndPoint device, open a CIFS/SMB share on an IP address or an HTTP(S) request on an IP address to an IIS web server configured for NTLM authentication. This server can be part of the created subscription, but it’s not a requirement as the DC handles the authentication.

The 4624 event will appear in the security event log of the DC where a connection is made. If properly configured, this event will be forwarded to the log collector within 30 seconds.

Troubleshooting

Although Windows Event Forwarding is a powerful tool for collecting and centrally managing Windows events, challenges and issues can sometimes arise during its implementation. This chapter is dedicated to identifying, diagnosing, and resolving problems that may occur with Windows Event Forwarding. I will cover various common issues along with steps and techniques to effectively address them. By becoming familiar with troubleshooting, you can ensure that the Windows Event Forwarding implementation runs smoothly and that important data is always available for analysis.

Event log locations

  • Application and Services Logs – Microsoft – Windows
  • EventLog-Forwarding Plugin (log)
  • Windows Remote Management (log)
  • Event Collector (log)

Firewall rules

  • Windows Firewall ports Windows Remote Management (HTTP-In) Port 5985 configured for inbound communication.
  • Windows Firewall ports Windows Remote Management (HTTP-In) – Compatibility Mode – Port 80 configured for inbound communication.
  • Windows Firewall ports Windows Remote Management (HTTPs-In) configured for inbound communication.

Basic firewall connectivity

Test-NetConnection -ComputerName prod-mon.corp.michaelwaterman.nl -port 5985

Check WinRM connectivity

winrm id -remote:<source_computer_name> -auth:none

WinRM settings

WinRM client configuration

winrm get winrm/config/client/auth

WinRM server configuration

winrm get winrm/config/service/auth

WinRM service configuration

winrm get wmi/root/cimv2/Win32_Service?Name=WinRM

Reset WinRM to default

winrm invoke restore winrm/config @{}

WinRM related security groups

  • Local administration.
  • Domain administrator

Display all registered machines to the subscription

wecutil gr <Subscription>

All about NTLM values

LM-manager (LM) authentication is the protocol used to authenticate Windows clients for network operations, including domain memberships, access to network resources, and user or computer authentication. The LM authentication level determines which challenge/response authentication protocol is negotiated between the client and server computers. Specifically, the LM authentication level determines which authentication protocols the client will attempt to negotiate or which the server will accept. The value set for LmCompatibilityLevel determines which challenge/response authentication protocol is used for network logons. This value affects the level of the authentication protocol used by clients, the level of session security negotiated, and the level of authentication accepted by servers.

Value Setting Description
0 Send LM & NTLM responses. EndPoints use LM and NTLM authentication and never use NTLMv2 session security. Domain controllers accept LM, NTLM, and NTLMv2 authentication.
1 Send LM & NTLM – use NTLMv2 session security if negotiated. EndPoints use LM and NTLM authentication and use NTLMv2 session security if the server supports it. Domain controllers accept LM, NTLM, and NTLMv2 authentication.
2 Send NTLM response only. EndPoints use only NTLM authentication and use NTLMv2 session security if the server supports it. Domain controllers accept LM, NTLM, and NTLMv2 authentication.
3 Send NTLMv2 response only.

(Windows 7+ default)

EndPoints use only NTLMv2 authentication and use NTLMv2 session security if the server supports it. Domain controllers accept LM, NTLM, and NTLMv2 authentication.
4 Send NTLMv2 response only/refuse LM. EndPoints use only NTLMv2 authentication and use NTLMv2 session security if the server supports it. Domain controllers refuse LM authentication and only accept NTLM and NTLMv2 authentication.
5 Send NTLMv2 response only/refuse LM & NTLM. EndPoints use only NTLMv2 authentication and use NTLMv2 session security if the server supports it. Domain controllers refuse LM and NTLM authentication and only accept NTLMv2 authentication.

Additional info

This chapter contains various references that are not included in the main part of the post and are intended to further support the NTLM traffic inventory process.

NTLM Registry key settings

  • Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
  • Value: LmCompatibilityLevel
  • Type: DWORD

PowerShell for auditing activation

# Audit NTLM Authentication in this domain: Enable all - Domain Controllers Only
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\services\Netlogon\Parameters' -Name AuditNTLMInDomain -Value 7

# Audit incoming NTLM traffic: Enable auditing for all accounts
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0' -Name AuditReceivingNTLMTraffic -Value 2

# Restrict NTLM: Outgoing NTLM traffic to remote servers: Audit All
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0' -Name RestrictSendingNTLMTraffic -Value 1

Final thoughts

Implementing Windows Event Forwarding (WEF) is a powerful way to enhance your organization’s security and monitoring capabilities. By centralizing event logs and focusing on NTLM v1 traffic, you can gain valuable insights into your network’s authentication processes and identify potential security risks.

While setting up WEF may require some initial effort and configuration, the benefits of having a comprehensive, real-time view of your network’s activities are well worth it. This guide has provided you with the necessary steps and considerations to get started, but remember that ongoing monitoring and adjustment are key to maintaining an effective security posture.

Keypoints

NTLM poses a security risk and should be disabled

  • Many vulnerabilities are based on NTLM
  • NTLM has been replaced by Kerberos and is used for backward compatibility and as fallback mechanism
  • Blocking NTLM can have an impact on services
  • Configuration errors and exceptions can be identified with an analysis over several months
  • NTLM can be blocked within the domain after exceptions have been defined

Security researchers have found many vulnerabilities in Microsoft products in recent months which, in the worst case, allow to escalate privileges from non-authenticated access to the domain administrator. These include ProxyLogon (CVE-2021-26855, CVE-2021-27065) and ProxyShell (CVE-2021-34473, CVE-2021-34523, CVE-2021-31207) by Orange Tsai, PetitPotam (VDB-179650) by topotam, and various vulnerabilities in insecurely configured Active Directory Certificate Services (ADCS) by Will Schroeder and Lee Christensen. A common denominator is the use or misuse of the New Technology LAN Manager (NTLM) authentication protocol.

Attackers try to force NLTM authentication of a user or machine in order to abuse it for their own purposes. This technique is called Coerced Authentication or Forced Authentication. This can be achieved via direct requests or indirectly via machine-in-the-middle attacks (MITM) as well as ARP or multicast poisoning. The tool Responder by Laurent Gaffie is a popular and reliable tool for the latter attack technique. Attackers can use the forced NTLM authentication to crack credentials from the challenge response hashes or relay them to another system. An overview of NTLM relay attacks is shown in Charlie Bromberg’s mind map and the attack techniques are documented on the NTLM relay attacks page.

NTLM relay attack mind map by thehacker.recipes

NTLM poses a security risk and should be disabled.

Introduction

The NTLM protocol is a challenge response authentication and uses different protocols for this. The term NTLM should not be mistaken for the hash function of Windows. Windows stores the hash of passwords locally in the SAM database and on domain controllers in the file ntds.dit and uses the hash function NTHash, which uses the algorithm MD4(UTF-16-LE(password)). NTHash is often incorrectly referred as NTLM.

NTLM uses the following protocols:

  • LAN Manager Version 1 (LM)
  • LAN Manager Version 2 (LMv2)
  • NT LAN Manager Version 1 (NTLMv1 or Net-NTLMv1)
  • NT LAN Manager Version 2 (NTLMv2 or Net-NTLMv2)
  • NT LAN Manager 2 – Session Security

The functionality of the protocols is explained in detail in the article The NTLM Authentication Protocol and Security Support Provider. NTLMv2 is supported since Windows NT 4.0 SP4. The Kerberos protocol has been the primary and preferred authentication method in an Active Directory infrastructure since Windows 2000. However, NTLM is still active by default in Windows 10 and Windows Server 2019 for compatibility reasons. NTLM is used for authentication if no AD infrastructure is available, authentication with systems outside the domain takes place, systems are addressed via the IP address instead of hostnames or DNS, or no domain controller can be reached using Kerberos.

Disable NTLM

Backward compatibility and the use as fallback protocol makes it difficult to disable NTLM. Therefore, outages could occur if NTLM is disabled on all systems without any prior investigation. The “Microsoft veteran” and principal program manager in the area of Windows Server Engineering Ned Pyle already wrote back in 2009 in the TechNet article NTLM Blocking and You: Application Analysis and Auditing Methodologies in Windows 7 that blocking NTLM is not easy and requires an analysis and longer preparation.

Audit of NTLM

There are three group policies under the path Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Security Options, and the recommended setting to perform an analysis is:

Setting Value
Network security: Restrict NTLM: Audit Incoming NTLM Traffic Enable auditing for all accounts
Network security: Restrict NTLM: Audit NTLM authentication in this domain Enable all
Network security: Restrict NTLM: Outgoing NTLM traffic to remote servers Audit all

The Audit NTLM authentication in this domain policy should only be applied to domain controllers, the other two can be applied to all systems. The NTLM audit events are logged to the event log Applications And Services Logs\Microsoft\Windows\NTLM\Operational.

Analysis

All events are ideally collected and analysed in a central logging/monitoring infrastructure. For example with Splunk, the following entry can be added to the SplunkForwarder configuration in inputs.conf:

[WinEvent Log://Microsoft-Windows-NTLM/Operational]
checkpointInterval = 5
current_only = 0
disabled = 0
start_from = oldest

The objective is to identify which systems use NTLM for authentication. NTLM is used in various protocols such as HTTP or SMB. The following Splunk query can be used to generate a list of IP addresses of target servers:

source="winEvent Log*" "LogName=Microsoft-Windows-NTLM/Operational"
| rex field=_raw "(?i)target\sserver:\s(?<IP>.*)" 
| dedup IP
| table IP

This list is a starting point for analysing which systems and applications use NTLM. For this purpose, the log data of clients and servers are correlated. In events with the event id 8003, the incoming authentication request is logged on the server. The user, domain and workstation can be extracted from this message. At the same time, the outgoing connection is logged on the client under the event id 8001. In the case of applications that do not communicate over SMB, the target server, and the process (Name of client process) can be identified.

In the following example, the user jdoe accesses a web application with activated Windows Authentication via IP address:

Message=NTLM client blocked audit: Audit outgoing NTLM authentication traffic that would be blocked.
Target server: HTTP/192.168.1.112
Supplied user: jdoe
Supplied domain: TEST
PID of client process: 5780
Name of client process: C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe
LUID of client process: 0xBE4B5
User identity of client process: jdoe
Domain name of user identity of client process: TEST

The client client01 establishes a connection to the web server web01 via the URL https://192.168.1.112. Authentication is necessary for access and since the IP address is used, the web server and browser agree on the NTLM protocol. The user enters his domain credentials, the web server accepts it and validates the credentials with the help of a domain controller. Based on the analysis of the logs, it is evident that an outgoing NTLM connection to 192.168.1.112 is established on the client (event id 8001), the NTLM connection is received on the web server (event id 8002) and the web server forwards the credentials for validation to a DC (event id 8004).

The audit phase should be continued over several months. Within this phase, log data can already be analysed and possible misconfigurations corrected. An example of a misconfiguration is that an IP address has been configured for access instead of the NetBIOS server name or the fully qualified domain name (FQDN).

If the service or application does only support NTLM, it must be registered as exception. However, the objective is to have as few exceptions as possible.

At the end of the audit phase, an exception list should be available containing all systems that receive incoming NTLM connections and from which systems access must be possible. The completeness of the list is essential for the functionality of the infrastructure. As soon as NTLM is blocked and a system is not on the list, this application will no longer work.

Blocking NTLM

When NTLM is blocked, it is not completely disabled on a system because the local login process still uses NTLM. Even if NTLM is blocked, logging in with a local account is still possible.

There are three group policies for blocking NTLM under the path Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Security Options, and the settings to block NTLM completely are:

Setting Value
Network security: Restrict NTLM: Incoming NTLM traffic Deny all accounts
Network security: Restrict NTLM: NTLM authentication in this domain Deny all
Network security: Restrict NTLM: Outgoing NTLM traffic to remote servers Deny all

The settings Incoming NTLM traffic and Outgoing NTLM traffic to remote servers can be configured on all systems. The setting NTLM authentication in this domain is relevant for domain controllers.

If exceptions for blocking are necessary, the settings are available under the path Computer Configuration\Policies\Windows Settings\Security Settings\Local Policies\Security Options:

  • Network security: Restrict NTLM: Add remote server exceptions for NTLM authentication
  • Network security: Restrict NTLM: Add server exceptions in this domain

The setting Add remote server exceptions for NTLM authentication defines which systems a client can still authenticate to via NTLM. The NetBIOS name, FQDN and IP address are accepted as valid values. The list of systems that continue to accept NTLM requests and are within the domain must be included in the Add server exceptions in this domain setting. This setting is maintained on domain controllers.

Example

NTLM is to be blocked in this environment. Incoming and outgoing NTLM connections can be blocked on all systems of a domain. On the domain controllers, the use of NTLM within the domain is additionally deactivated. An exception list is also maintained on the domain controllers. In addition, outgoing NTLM connections must be declared as exceptions on the involved systems. This list should be divided among the requirements and not distributed as a complete list.

A web application that uses an IIS web server with Windows Authentication was specified as an exception. The following systems are involved for this exception. The DC dc01 is an example for all domain controllers in the domain.

Hostname IP address
dc01 192.168.1.101
web01 192.168.1.112
client01 192.168.1.201

The restriction Outgoing NTLM traffic to remote servers only affects client01 in this example, as the outgoing NTLM connection to web01 is blocked there (Event ID 4001). Therefore, the IP address of web01 is included in the list of the setting Add remote server exceptions for NTLM authentication. Ideally, the exception list is only assigned to clients that need access to the web application.

Due to the setting Incoming NTLM traffic being set to the value Deny all accounts, the NTLM connection from client01 to web01 is blocked on the web server (Event ID 4002). According to the documentation of Microsoft, the exception list Add server exceptions in this domain can be used for Incoming NTLM traffic. However, this exception did not work in the test environment, so the setting Incoming NTLM traffic had to be configured to the value Allow all on web01.

To disable NTLM within the domain, the setting NTLM authentication in this domain is set to the value Deny all. The NTLM authentication request of the web server will be blocked on the DC (Event ID 4004). Therefore, web01 is added to the list of the Add server exceptions in this domain setting. In the test environment, the NetBIOS server name had to be configured; if the FQDN was used, the exception did not work.

The configuration for the systems including exceptions is as follows:

Hostname Setting Value
dc01 Incoming NTLM traffic Deny all accounts
dc01 NTLM authentication in this domain Deny all
dc01 Outgoing NTLM traffic to remote servers Deny all
dc01 Add server exceptions in this domain web01
web01 Incoming NTLM traffic Allow All
web01 Outgoing NTLM traffic to remote servers Deny all
client01 Incoming NTLM traffic Deny all accounts
client01 Outgoing NTLM traffic to remote servers Deny all
client01 Add remote server exceptions for NTLM authentication 192.168.1.112

Conclusion

The authentication protocol NTLM is outdated and insecure and was replaced by Kerberos. Since then, NTLM has continued to be supported for compatibility reasons and is still active in the current Windows version. NTLM is misused for many attacks and makes it easier for attackers to compromise an Active Directory infrastructure.

The task of blocking NTLM must be implemented in several steps. First, it must be determined which systems and services still use NTLM. The audit settings should be enabled, and the logs analysed over months with the goal of finding incorrect configurations and reducing NTLM use. For systems that continue to depend on NTLM, exception lists can be documented and configured. Afterwards, NTLM can be disabled within the domain.

The hurdle to block NTLM is high, it is not an easy task to achieve and there is a risk of failures. But given the many attacks and vulnerabilities in NTLM, the security benefit is so substantial that it is worth tackling the project. It is time to say goodbye to NTLM. Farewell.

About the Author

Michael Schneider has been in IT since 2000. Since 2010 he is focused on information security. He is an expert at penetration testing, hardening and the detection of vulnerabilities in operating systems. He is well-known for a variety of tools written in PowerShell to find, exploit, and mitigate weaknesses. (ORCID 0000-0003-0772-9761)

Links

  • http://davenport.sourceforge.net/ntlm.html
  • https://attack.mitre.org/techniques/T1187/
  • https://blog.orange.tw/2021/08/proxylogon-a-new-attack-surface-on-ms-exchange-part-1.html
  • https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-restrict-ntlm-incoming-ntlm-traffic
  • https://g-laurent.blogspot.com/
  • https://github.com/lgandx/Responder
  • https://github.com/topotam/PetitPotam
  • https://specterops.io/assets/resources/Certified_Pre-Owned.pdf
  • https://techcommunity.microsoft.com/t5/ask-the-directory-services-team/ntlm-blocking-and-you-application-analysis-and-auditing/ba-p/397191
  • https://twitter.com/NerdPyle
  • https://twitter.com/_nwodtuhs
  • https://twitter.com/harmj0y
  • https://twitter.com/orange_8361
  • https://twitter.com/tifkin_
  • https://twitter.com/topotam77
  • https://vuldb.com/?id.170592
  • https://vuldb.com/?id.170595
  • https://vuldb.com/?id.174834
  • https://vuldb.com/?id.178577
  • https://vuldb.com/?id.178612
  • https://vuldb.com/?id.179650
  • https://www.thehacker.recipes/ad-ds/movement/ntlm/relay

Усиливаем безопасность. Переключаемся с протокола NTLMv1 на NTLMv2. Лучше, конечно, использовать Kerberos, но хорошего понемногу.

Недостатки протокола NTLMv1:

  • слабое шифрование
  • хранение хэша пароля в оперативной памяти в службе LSA, благодаря чему можно извлечь пароли из памяти Windows в открытом виде (!) с помощью утилит типа mimikatz и использовать хэш для дальнейших атак с помощью сценариев Pass-The-Hash
  • отсутствие взаимной проверки подлинности клиента и сервера, что даёт возможность атаки перехвата данных NTLM и неавторизованного доступа к ресурсам сети

Часть этих недостатков исправлена в новой версии NTLMv2, которая использует более криптостойкие алгоритмы шифрования и позволяет предотвратить популярные атаки на NTLM. Начиная с Windows 7 / Windows Server 2008 R2 протоколы аутентфикации NTLMv1 и LM по умолчанию отключены.

Переключаемся с протокола NTLMv1 на NTLMv2 с помощью GPO. Переходим в консоль управления Group Policy Management (gpmc.msc), редактируем Default Domain Controllers Policy.

Редактируем политику. Computer Configuration → Policies → Windows Settings → Security Settings → Local Policies → Security Options. Нас интересует раздел Network Security: LAN Manager authentication level (Сетевая безопасность: уровень проверки подлинности LAN Manager).

win

Доступны опции (от менее безопасной к более безопасной):

  • Send LM & NTLM responses
  • Send LM & NTLM responses – use NTLMv2 session security if negotiated
  • Send NTLM response only
  • Send NTLMv2 response only
  • Send NTLMv2 response only. Refuse LM
  • Send NTLMv2 response only. Refuse LM& NTLM

По умолчанию в Windows 7 и выше используется настройка Send NTLMv2 response only (Отправлять только NTLMv2-ответ). При этой настройке клиентские компьютеры используют NTLMv2 аутентификацию, но контролеры домены принимают LM, NTLM, и NTLMv2 запросы.

Можно изменить значение политики на более безопасную опцию Send NTLMv2 response only. Refuse LM & NTLM. При этой политике контролеры домена будут отвергать запросы LM и NTLM.

То же самое можно сделать через ветку реестра HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa с помощью параметра DWORD с именем LmCompatibilityLevel и значением от 0 до 5. Значение 5 соответствует значению политики Отправлять только NTLMv2-ответ. Отказывать LM и NTLM.

NTLM (NT LAN Manager) is a legacy Microsoft authentication protocol that dates back to Windows NT. Although Microsoft introduced the more secure Kerberos authentication protocol back in Windows 2000, NTLM (mostly NTLMv2) is still widely used for authentication on Windows domain networks. In this article, we will look at how to disable the NTLMv1 and NTLMv2 protocols and switch to Kerberos in an Active Directory domain.

Contents:

  • How to Enable NTLM Authentication Audit Logging?
  • Configuring Active Directory to Force NTLMv2 via GPO
  • Restrict NTLM Completely and Use Kerberos Authentication in an AD

The key NTLMv1 problems:

  • weak encryption;
  • storing password hash in the memory of the LSA service, which can be extracted from Windows memory in plain text using various tools (such as Mimikatz) and used for further attacks using pass-the-has scripts;
  • the lack of mutual authentication between a server and a client, leading to data interception and unauthorized access to resources (some tools such as Responder can capture NTLM data sent over the network and use them to access the network resources);
  • and other vulnerabilities.

Some of these have been in the next version NTLMv2 which uses more secure encryption algorithms and allows to prevent of common NTLM attacks. NTLMv1 and LM authentication protocols are disabled by default starting with Windows 7 and Windows Server 2008 R2.

How to Enable NTLM Authentication Audit Logging?

Before completely disabling NTLM in a domain and switching to Kerberos, it is a good idea to ensure that there are no applications in the domain that require and use NTLM auth. There may be legacy devices or services on your network that still use NTLMv1 authentication instead of NTLMv2 (or Kerberos).

To track accounts or apps that use NTLM authentication, you can enable audit logging policies on all computers using GPO. Open the Default Domain Controller Policy, navigate to the Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> Security Options section, find and enable the Network Security: Restrict NTLM: Audit NTLM authentication in this domain policy and set its value to Enable all.

Network Security: Restrict NTLM: Audit NTLM authentication in this domain

In the same way, enable the following policies in the Default Domain Policy:

  • Network Security: Restrict NTLM: Audit Incoming NTLM Traffic – set its value to Enable auditing for domain accounts
  • Network security: Restrict NTLM: Outgoing NTLM traffic to remote servers: set Audit all

Network Security: Restrict NTLM: Audit Incoming NTLM Traffic

Once these policies are enabled, events related to the use of NTLM authentication will appear in the Application and Services Logs-> Microsoft -> Windows -> NTLM section of the Event Viewer.

You can analyze the events on each server or collect them from the central Windows Event Log Collector.

You need to search for the events from the source Microsoft-Windows-Security-Auditing with the Event ID 4624 – “An Account was successfully logged on“. Note the information in the “Detailed Authentication Information” section. If there is NTLM in the Authentication Package value, then the NTLM protocol was used to authenticate this user.

Look at the value of Package Name (NTLM only). This line shows which protocol (LM, NTLMv1, or NTLMv2) was used for authentication. So you need to identify any servers/applications that are using the legacy protocol.

eventid 4624 source Microsoft-Windows-Security-Auditing ntlm usage

Also, if NTLM is used for authentication instead of Kerberos, Event ID 4776 will appear in the log:

The computer attempted to validate the credentials for an account
Authentication Package: MICROSOFT_AUTHENTICATION_PACKAGE_V1_0

For example, to search for all NTLMv1 authentication events on all domain controllers, you can use the following PowerShell script:

$ADDCs = Get-ADDomainController -filter
$Now = Get-Date
$Yesterday = $Now.AddDays(-1)
$NewOutputFile = "c:\Events\$($Yesterday.ToString('yyyyddMM'))_AD_NTLMv1_events.log"
function GetEvents($DC){
Write-Host "Searching log on " $DC.HostName
$Events = Get-EventLog "Security" -After $Yesterday.Date -Before $Now.Date -ComputerName $DC.HostName -Message "*NTLM V1*" -instanceid 4624
foreach($Event in $Events){
Write-Host $DC.HostName $Event.EventID $Event.TimeGenerated
Out-File -FilePath $NewOutputFile -InputObject "$($Event.EventID), $($Event.MachineName), $($Event.TimeGenerated), $($Event.ReplacementStrings),($Event.message)" -Append
}
}
foreach($DC in $ADDCs){GetEvents($DC)}

Once you have identified the users and applications that use NTLM in your domain, try switching them to use Kerberos (possibly using SPN). To use Kerberos authentication, some applications need to be slightly reconfigured (Kerberos Authentication in IIS, Configure different browsers for Kerberos authentication, Create a Keytab File Using Kerberos Auth). From my own experience, I see that even large commercial products are still using NTLM instead of Kerberos, some products require updates or configuration changes. The idea is to identify which applications use NTLM authentication, and now you have a way to identify that software and devices.

Small open-source products, old models of various network scanners (which store scans in shared network folders), some NAS devices and other old hardware, legacy software, and operating systems are likely to have authentication problems when NTLMv1 is disabled.

Those apps that cannot use Kerberos can be added to the exceptions. This allows them to use NTLM authentication even if it is disabled at the domain level. To do it, the Network security: Restrict NTLM: Add server exceptions for NTLM authentication in this domain policy is used. Add the names of the servers (NetBIOS names, IP addresses, or FQDN), on which NTLM authentication can be used, to the list of exceptions as well. Ideally, this exception list should be empty. You can use the wildcard character *.

GPO: Network security: Restrict NTLM: Add server exceptions for NTLM authentication in this domain

To use Kerberos authentication in an application, you must specify the DNS name of the server, instead of its IP address. If you specify an IP address when connecting to your resources, NTLM authentication will be used.

Configuring Active Directory to Force NTLMv2 via GPO

Before completely disabling NTLM in an AD domain, it is recommended that you first disable its more vulnerable version, NTLMv1. The domain administrator needs to make sure that their network does not allow the use of NTLM or LM for authentication, as in some cases an attacker can use special requests to get a response to an NTLM/LM request.

You can set the preferred authentication type using the domain GPO. Open the Group Policy Management Editor (gpmc.msc) and edit the Default Domain Controllers Policy. Go to the GPO section Computer Configurations -> Policies -> Windows Settings -> Security Settings -> Local Policies -> Security Options and find the policy Network Security: LAN Manager authentication level.

Network Security: LAN Manager authentication level - disable ntlm v1 and lm

There are 6 options to choose from in the policy settings::

  • Send LM & NTLM responses;
  • Send LM & NTLM responses – use NTLMv2 session security if negotiated;
  • Send NTLM response only;
  • Send NTLMv2 response only;
  • Send NTLMv2 response only. Refuse LM;
  • Send NTLMv2 response only. Refuse LM& NTLM.

The NTLM authentication options are listed in the order of their security improvement. By default, Windows 7 and later operating systems use the option Send NTLMv2 response only. If this option is enabled, client computers use NTLMv2 authentication, but AD domain controllers accept LM, NTLM, and NTLMv2 requests.

NTLMv2 can be used where the Kerberos protocol has failed and for some operations (for example, to authenticate local groups and accounts on the domain-joined computers) or in workgroups.

You can change the policy value to the most secure option 6 : “Send NTLMv2 response only. Refuse LM & NTLM”. This policy causes domain controllers to reject LM and NTLM requests as well.

You can also disable NTLMv1 through the registry. To do this, create a DWORD parameter with the name LmCompatibilityLevel with a value between 0 and 5 under the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa. Value 5 corresponds to the policy option “Send NTLMv2 response only. Refuse LM NTLM”.

Make sure that the Network security: Do not store LAN Manager hash value on next password change policy is enabled in the same GPO section. It is enabled by default starting with Windows Vista / Windows Server 2008 and prevents the creation of an LM hash.

Network security: Do not store LAN Manager hash value on next password change

Once you have ensured that you are not using NTLMv1, you can go further and try to disable NTLMv2. NTLMv2 is a more secure authentication protocol but loses significantly to Kerberos in terms of security (although there are fewer vulnerabilities in NTLMv2 than in the NTLMv1, but there is still a chance of capturing and reusing data, as well as it doesn’t support mutual authentication).

The main risk of disabling NTLM is the potential use of legacy or misconfigured applications that may still be using NTLM authentication. If this is the case, they will need to be updated or specially configured to switch to Kerberos.

If you have a Remote Desktop Gateway server on your network, you will need to make an additional configuration to prevent clients from connecting using NTLMv1. Create a registry entry:

REG add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\TerminalServerGateway\Config\Core" /v EnforceChannelBinding /t REG_DWORD /d 1 /f

Restrict NTLM Completely and Use Kerberos Authentication in an AD

To check how authentication works in different applications in a domain without using NTLM, you can add the accounts of the required users to the Protected Users domain group (it has been available since the Windows Server 2012 R2 release). Members of this security group can only authenticate using Kerberos (NTLM, Digest Authentication, or CredSSP are not allowed). This allows you to verify that Kerberos user authentication is working correctly in different apps.

Then you can completely disable NTLM on the Active Directory domain using the Network Security: Restrict NTLM: NTLM authentication in this domain policy.

The policy has 5 options:

  • Disable: the policy is disabled (NTLM authentication is allowed in the domain);
  • Deny for domain accounts to domain servers: the domain controllers reject NTLM authentication attempts for all servers under the domain accounts, and the “NTLM is blocked” error message is displayed;
  • Deny for domain accounts: the domain controllers are preventing NTLM authentication attempts for all domain accounts, and the “NTLM is blocked” error appears;
  • Deny for domain servers: NTLM authentication requests are denied for all servers unless the server name is on the exception list in the “Network security: Restrict NTLM: Add server exceptions for NTLM authentication in this domain” policy;
  • Deny all: the domain controllers block all NTLM requests for all domain servers and accounts.

GPO: Network Security: Restrict NTLM: NTLM authentication in this domain

Although NTLM is now disabled on the domain, it is still used to process local logins to computers (NTLM is always used for local user logons).

You can also disable incoming and outgoing NTLM traffic on domain computers using separate Default Domain Policy options:

  • Network security: Restrict NTLM: Incoming NTLM traffic = Deny all accounts
  • Network security: Restrict NTLM: Outgoing NTLM traffic to remote servers = Deny all

After enabling auditing, Event Viewer will also display EventID 6038 from the LsaSRV source when using NTLM for authentication:

Microsoft Windows Server has detected that NTLM authentication is presently being used between clients and this server. This event occurs once per boot of the server on the first time a client uses NTLM with this server.
NTLM is a weaker authentication mechanism. Please check:
Which applications are using NTLM authentication?
Are there configuration issues preventing the use of stronger authentication such as Kerberos authentication?
If NTLM must be supported, is Extended Protection configured?

eventid 6038 from lsasrv source: NTLM authentication is presently being used between clients and this server

You can check that Kerberos is used for user authentication with the command:

klist sessions

klist session - check authentication protocol used

This command shows that all users are Kerberos-authenticated (except the built-in local Administrator, who is always authenticated using NTLM).

If you are experiencing a lot of user account lockout events after disabling NTLM, take a close look at the events with ID 4771 (Kerberos pre-authentication failed). Check the Failure Code in the error description. This will indicate the reason and source of the lock.

To further improve Active Directory security, I recommend reading these articles:

  • Securing administrator accounts in Active Directory
  • How to Disable LLMNR and NetBIOS over TCP/IP?

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как удалить nvidia physx windows 10
  • Какая версия операционной системы windows реализует плиточный интерфейс
  • Avrdude driver windows 10
  • Самый лучший аудиоплеер для windows 10 на русском
  • Как узнать параметры видеокарты на компьютере windows 10