- Централизованный сбор логов в Windows с разных компьютеров штатными средствами
- Adam the Automator
- How To Set Up Windows Event Log Forwarding In Windows Server 2016
- Jeff Christman
- Windows Event Log Forwarding Overview
- WEF Project Overview
- Environment and Knowledge Requirements
- Configuring the Event Log Collector
- Enabling WinRM on the Collector
- Starting the Subscription Collector Service
- Setting up the Forwarders’ GPO
- Allowing the Network Service to Read Event Logs
- Setting up a Subscription
- Verifying the WEF Configuration
- Your Takeaways
Централизованный сбор логов в Windows с разных компьютеров штатными средствами
А вы в курсе, что в винде, начиная с 2008R2 есть замечательная возможность – собирать логи с разных компьютеров в сети, в одном месте? Эта функция называется Windows Event Forwarding. Сегодня покажу как её настроить.
Настраивать функцию можно двумя способами.
Collector Initiated – это когда сервер, на который должны поступать все записи о событиях сам шлет запросы на машины в сети, и получает с них логи.
Source initiated – когда, компьютеры сами стучаться на сборщик и отправляют ему информацию. Настройка тут производится посредством GPO, где указывается адрес сборщика событий.
Я покажу как собирать логи на примере Collector Initiated.
Первым делом, необходимо настроить машины, с которых нужно собирать логи.
Для этого на них должно быть включено удаленное управление, или другими словами – должен быть настроен winrm. Чтобы его настроить необходимо выполнить команду от имени администратора:
Либо можно воспользоваться powershell
Дальше необходимо добавить учетную запись пользователя, или компьютера, на который будут отправляться логи (если вы по какой-то причине не захотите указывать при настройке учетную запись пользователя) в группу Event Log Readers. Но, в некоторых случаях членства в данной группе может быть недостаточно, тогда придется добавлять учетки в группу администратора.
Также если вы хотите собирать журналы безопасности, тогда придется учетной записи Network Service дать право на их чтение. Сделать это можно командой:
Тут все указанные SIDы – стандартные, мы добавляем запись (A;;0x1;;;S-1-5-20).
Для верности, вы можете посмотреть, что у вас указано командой
Если у вас много компьютеров, тогда процесс выдачи прав можно сильно упростить выполнив команду в PowerShell:
Как вы поняли, в папке, откуда вы выполните эту команду должно быть 2 файла:
Computers.txt – список компьютеров, на которых нужно выполнить команду. Каждый – с новой строки.
Security.ps1 – тут только наша команда — wevtutil set-log security /ca:O:BAG:SYD:(A;;0xf0005;;;SY)(A;;0x5;;;BA)(A;;0x1;;;S-1-5-32-573)(A;;0x1;;;S-1-5-20)
На этом настройка отдающих – завершена. Переходим к настройке сервера, где всё будет храниться.
Первым делом включим службу Windows Event Collector, для этого, от имени администратора выполним:
В оснастке службы должна будет появиться данная служба, с типом запуска Delayed Start.
Следующим шагом укажем физическое расположение файла журнала, т.к. если вы задумались о централизованном сборе логов, то их наверняка у вас будет не мало. По этому, лучше под это мероприятие выделить отдельный диск, на который и будут писаться события. Также лучше бы его ограничить по размеру, к примеру 2ГБ, что бы логами можно было относительно комфортно пользоваться.
Запускаем оснастку просмотр событий – eventvwr.msc, windows logs, правой кнопкой по Forwarded Events. И ограничиваем размер, чтобы логи не терялись – лучше выбрать Archieve the log when full, do not owerride events. И конечно указываем путь, где файл должен лежать.
Дальше, создадим подписку – правой кнопкой по Subscriptions – Create Subscription
Тут нужно ввести имя, выбрать лог, куда должны складываться события (по умолчанию – Forwarded Events, по этом ему мы и меняли расположение и размер).
Сразу идем в Advanced Settings и указываем пользователя, от имени которого будет действовать сборщик (если вы указывали имя компьютера ранее на клиентах, тогда этот шаг пропускаем).
Выбираем события, которые должны собираться – select events. Тут можете настроить под себя, как вам угодно. Но не стоит выбирать абсолютно всё, то есть и стандартные логи, и логи приложений, иначе практически наверняка у вас выскочит ошибка, во время сбора логов, о слишком большом запросе.
Осталось только добавить компьютеры, с которых хотим собирать информацию – select computers. После добавления каждого из компьютеров лучше сразу жать test, чтобы удостовериться, что всё будет работать как надо.
Выжидаем некоторое время, и смотрим на статус созданного коллектора. Если он активный, значит в скором времени в forwarded events начнут появляться записи.
Но на этом еще не всё. Когда к вам начнут прилетать записи, вы скорее всего увидите, что для записи отсутствуют описания. Что-то вроде:
The description for Event ID X from source A cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
Частично данную незадачу можно решить, выполнив команду:
И перезапустив службу Windows Event Collector. По умолчанию, за место events установлен RenderedText. И по умолчанию события пререндерятся на удаленных компьютерах и отправляются с локализованными строками, из-за чего есть вероятность, что события не будут распознаны. Кроме того, изменение на Events немного снизит нагрузку на сеть и компьютеры – источники.
Но и после изменения параметра /cf проблема может уйти только частично. Как правило, указанные выше записи будут появляться для каких-то костюмных служб, которых нет на сборщике, например Exchange или SharePoint или еще что-то.
В событии внизу будет указано, кто является источником сообщения, из чего можно сделать вывод – чего не хватает.
Все источники и то, на какие DLL они завязаны можно посмотреть в реестре – HKLM\SYSTEM\CurrentControlSet\services\eventlog. Тут всё разбито по логам, типа Application, System и т.п. Соответственно если нужного источника тут нет, то его необходимо экспортировать с компьютера, где он есть. Соответственно и нужные, как правило, DLLки, со словарями можно посмотреть в этих ветках реестра – это параметры, где есть file в названии. Пути до файлов, для удобства, после импорта можно менять.
Если события пишет небольшое приложение, то источников для него, скорее всего будет 1-2, и их можно спокойно перенести руками, но вот если это что крупное, например exchange, то источников там уже 147. Согласитесь, такое количество руками переносить – мазохизм. Поэтому был написан скрипт, который всё сделает за нас.
Что нужно делать:
Копируем скрипт export-log на сервер, где нужная служба есть, переходим в папку со скриптом и запускаем его от имени администратора с ключом, которым является часть имени источника событий. Например, если мы увидели в просмотре событий, что нет описаний для MSExchange Certificate, то скрипт можно запустить так:
Если источником событий является Microsoft-Sharepoint Foundation, то запустить можно с ключом sharepoint.
Скрипт создаст папку, пройдется по всем разделам eventlog, сделает дамп всех разделов, где в имени присутствует ключ, исходя из путей в параметрах скопирует в папку нужные файлы, а также создаст текстовый файл со списком сдампленных разделов.
Далее нужно скопировать созданную папку на сервер сборщик логов, в папку со скриптом import-log, перейти в powershell запущенном от имени администратора в папку со скриптом, и запустить его с тем же самым ключом.
Скрипт скопирует нужные файлы, импортирует записи в реестр, и изменит пути до файлов в параметрах. Я сделал, чтобы файлы копировались в папку C:\CustomEvents\[ключ], соответственно папка C:\CustomEvents\ должна существовать.
Возможно, чтобы до оснастки просмотр событий дошли изменения, её нужно будет перезапустить. Всё, теперь вы сможете читать логи на компьютере, где нет служб, которые эти логи сгенерировали.
Во время настройки этого хозяйства я столкнулся с некоторыми неприятными моментами, оставлю описание этих моментов тут.
- На парочке серверов были непонятки с WinRM. В диспетчере серверов статус удаленного управления был обозначен как неизвестный. При попытке выполнить winrm qc выскакивало сообщение
WinRM service is already running on this machine.
WSManFault
Message
ProviderFault
WSManFault
Message = Unable to check the status of the firewall.
Error number: -2147024894 0x80070002
The system cannot find the file specified.
Подключения к серверу не осуществлялось. -, с удаленной машины, упорно говорил, что служба не запущена.
Google настойчиво предлагал добавить правила в firewall:
Но для меня это результата не дало, равно как и его включение, отключение и изменение его конфигурации.
Как выяснилось, именно данная ошибка была связана с локализацией системы, на нее был установлен языковой пакет. После изменения языка системы – ошибка ушла, и команда отработала штатно, но доступа – не появилось.
Посмотрел на прослушиваемые порты командой netstat -ant — обнаружил, что порт winrm ( 5985) слушается только на адресе 127.0.0.1
показало, что iis слушает только на адресе 127.0.0.1
Помогло выполнение команд:
Вторая команда – необязательно, т.к. если в списке прослушиваемых адресов нет адресов, то прослушиваются все адреса системы.
2. Мы подцепили лог на диск iSCSI и после перезагрузки системы, данный лог стабильно отваливается. Связано это, скорее всего с тем, что после перезагрузки – iSCSI диски, либо переподключаются, либо изначально долго подключаются, и всё это происходит уже после запуска службы event log. Тут помогло указание в свойствах неправильного пути до лога, и когда система ругнется, что путь не верен – нужно указать верный путь, тогда файл подцепится.
Я добавил в планировщик заданий, на событие start up — простенький файл содержащий следующие строчки:
Adam the Automator
How To Set Up Windows Event Log Forwarding In Windows Server 2016
Jeff Christman
Read more posts by this author.
Event log management is a critical skill to learn in all Windows environments. Activity is being recorded to Windows event logs every second and it acts as not only a security tool but also as a vital troubleshooting aid.
Once a server environment goes past a few servers though, managing individual server event logs becomes unwieldy at best. Luckily, you have a feature called Windows Event Forwarding (WEF) to make it easier.
Table of Contents
Windows Event Log Forwarding Overview
WEF is a service that allows you to forward events from multiple Windows servers and collect them in one spot. The service has two main components; a forwarder and a collector. A collector is a service running on Windows server that collects all events sent to it from an event log forwarder.
The “link” between the forwarding server and a collector is known as a subscription.
Collectors serve as subscription managers that accept events and allow you to specify which event log alerts to collect from endpoints.
WEF Project Overview
This is a Project article where we cover how to build a project or implement a solution. Each section hereafter will be cumulative steps that build upon the previous.
For this project, you’re going to learn how to set up a basic WEF implementation. You’ll learn how to set up both a collector and how to forward events to a collector with a subscription.
You’ll learn how to:
- Set up and configure an event log collector on a Windows Server instance. This will be the Windows Server that all of the event log forwarders will send events to.
- Create a GPO which, when applied, will point applicable Windows Server instances to the collector to send events to.
- Configuring the types of events to send to the collector.
You will learn how to work through each step in the remainder of this article.
Environment and Knowledge Requirements
Before you get too far, let’s first ensure my environment is the same as yours. Please be sure you have the following items in place before starting:
- (2) Windows Server instances – You can use any Window Server instance of 2012 R2 or higher. In this article, I’ll be using Windows Server 2016.
- Active Directory
- GPO – A familiarity with Group Policy Objects will be required.
- WinRM- WinRM needs to be running on all clients. Not configured just running.
Configuring the Event Log Collector
The first task to perform is configuring one of your Windows Server instances as the collector. Recall that the collector is the one that receives incoming event logs from the forwarder.
Enabling WinRM on the Collector
Windows Server instances that forward events to the collector do so over PowerShell Remoting or WinRM. You’ll first have to ensure WinRM is available on your collector. If the collector is running Windows Server 2012 R2 and above, WinRM is enabled by default, but the Windows Firewall may be interfering.
Run the the Enable-PSRemoting PowerShell cmdlet with no parameters on the collector. Even if PowerShell Remoting is already enabled, it will skip the necessary steps.
To be sure, you can also run Invoke-Command -ComputerName -ScriptBlock <1>from a remote computer. If you don’t receive an error, PowerShell Remoting is working.
Starting the Subscription Collector Service
Now that PowerShell Remoting is enabled and listening, start the subscription collector service. The subscription collector service needs to also start up automatically when Windows Server boots up.
On the collector, open Event Viewer click on Subscriptions. The first time you open the Subscriptions option, Windows will ask if you want to start the Windows Event Log Collector Service and configured to start automatically. Click Yes to accept.
You can see an example of the message below.
Congratulations! You now have a collector configured. It’s now time set up a GPO which will instruct Windows Server instances to forward events to the collector.
Setting up the Forwarders’ GPO
The next step is to configure one or more Windows servers to begin forwarding event logs to the collector. The easiest way to do so is by creating a GPO. This GPO can then be applied to one or more OUs which contain the servers to send events from.
You’ll learn the basics of setting up the necessary settings in a GPO in this Project article. But if you’d like to a complete rundown with all the available options, check out the Microsoft documentation.
Allowing the Network Service to Read Event Logs
WEF uses the Network Service account to read and send events from a forwarder to a collector. By default, the Network Service account does not have access to do this. You’ll first need to set this ACL to allow it.
Note: Many of the event logs in Windows Server already provide the Network Service account access to the common event logs like Application and System. But the account is not given access to the Security event log and other custom event logs.
To allow the Network Service account to read event logs on event log forwarders, use a GPO. In this article, you’ll learn how to allow the Network Service account access to the Security event log. Other event logs will follow the same process.
1. Begin by opening up a command prompt and running wevtutil gl security . This will provide various information about the Security event log. But the piece to pay attention to is the channelAccess SDDL.
You can see below an example of the SDDL you’ll need for the Security event log. The channelAccess line represents the permissions set on the event log. Copy the SDDL highlighted below and save it somewhere for later to add to a GPO.
2. Create a GPO via the Group Policy Management Console. Inside of the GPO, navigate to Computer Configuration → Policies → Administrative Templates → Windows Components → Event Forwarding → Configure target subscription manager.
3. Set the value for the target subscription manager to the WinRM endpoint on the collector. You will set the Server to be in the format:
Note the Refresh interval at the end of the collector endpoint. The Refresh interval indicates how often clients should check in to see if new subscriptions are available.
4. Next, find the SDDL you copied earlier from running wevtutil gl security and paste it into the setting Computer Configuration → Policies → Administrative Templates → Windows Components → Event Log Service → Security → Configure log access.
Note that this SDDL will take precedence over all other permissions that have been configured for the event log.
You can see an example of what your GPO will look like below for the Security event log.
5. Once the GPO is created, you’ll then either link this GPO to an existing OU containing the Windows servers to send event logs from or create a new OU and link the GPO. Any AD computer account you add to this OU will now set up a subscription to the collector.
Setting up a Subscription
While configuring WEF to collect all events for all Windows servers in an Active Directory domain may seem like a good idea, it’s not. You must be selective and only forward events that are important to you. Filtering out the noise from what matters is where WEF demonstrates its true value.
Let’s work through setting up a subscription for the Security Event log.
Since you’ve already created the GPO and linked it to an Active Directory OU containing the Windows servers you’d like to send events from, the event sources are already set up
- On the collector, open the Windows Event Viewer and right-click on Subscriptions, then create subscription.
2. As shown below, select the Source computer initiated option and then click Select Computer Groups. This is where you will select which computers you’d like to forward events from.
Pro Tip: Selecting AD Groups. Ex: “Domain Controllers” will auto-populate any computers within the group. No need to select individual computers every time you add a new server.
3. Next select the events to forward. Opening up the query filter as you can see below, select Security to forward events to the collector from the Security event log.
4. Once the Security log is selected, you can filter down even more by entering the event ID, keywords, users and computers as shown below.
5. Click OK to exit from the Query Filter.
6. Click Advanced in the Subscription Properties window. Now select Minimize Latency. This setting will ensure the collector will receive events as soon as possible and also to help it catch up if it gets behind.
Verifying the WEF Configuration
Once WEF is set up, you should now check to see if the forwarders actually checked in by checking the Source Computers column on the main Subscriptions page.
You can also check the Event Forwarding Plugin Operational log under Applications and Services on the client to make sure everything is working. This is where you’ll see descriptive errors if something has gone awry with Kerberos or firewalls.
All that is left to to is find a low-value client, clear the Security log and see if you get an alert.
Your Takeaways
In this Project, you learned how to set up a basic WEF subscription. You:
- Set up an event collector
- Created a GPO to create a subscription on various Windows Server forwarders
- Configured a WEF subscription to only send specific events
- Ensured the WEF subscription sent events as fast as possible
WEF is a bit tricky to configure initially, but once up and running, you should have little problems and minimal maintenance headaches.