- Event Tracing
- Purpose
- Where applicable
- Developer audience
- Run-time requirements
- Process ETW traces in .NET code
- Event Tracing for Windows на стороне зла. Но это не точно
- Работа с ETW
- Следим за PowerShell
- S — значит бееезопасно
- Кейлоггер на PowerShell. Потому что могу.
- Нужно ли бояться
- Solving Windows Log Collection Challenges with Event Tracing
- About Event Tracing for Windows
- The Event Trace Data
- The Advantages of ETW
- The Challenges of ETW
- ETW in Real World Threat Hunting
- Using NXLog as a Single Agent Solution to Collect ETW Logs
Event Tracing
Purpose
Event Tracing for Windows (ETW) provides application programmers the ability to start and stop event tracing sessions, instrument an application to provide trace events, and consume trace events. Trace events contain an event header and provider-defined data that describes the current state of an application or operation. You can use the events to debug an application and perform capacity and performance analysis.
This documentation is for user-mode applications that want to use ETW. For information about instrumenting device drivers that run in kernel mode, see WPP Software Tracing and Adding Event Tracing to Kernel-Mode Drivers in the Windows Driver Kit (WDK).
Where applicable
Use ETW when you want to instrument your application, log user or kernel events to a log file, and consume events from a log file or in real time.
Developer audience
ETW is designed for C and C++ developers who write user-mode applications.
Run-time requirements
ETW is included in Microsoft WindowsВ 2000 and later. For information about which operating systems are required to use a particular function, see the Requirements section of the documentation for the function.
Process ETW traces in .NET code
You can use the .NET TraceProcessing API to analyze ETW traces for your applications and other software components. This API is used internally at Microsoft to analyze ETW data produced the Windows engineering system, and it is also used to power several tables in Windows Performance Analyzer. This API is available as a NuGet package.
Event Tracing for Windows на стороне зла. Но это не точно
В предыдущих статьях про сниффер на PowerShell и сбор данных о загрузке с удаленного сервера я уже немного писал про возможности ETW (Event Tracing for Windows). Сегодня я хочу подробнее рассказать про эту технологию.
Заодно покажу на примере разбора HTTPS и создания кейлоггера на PowerShell, как ее можно использовать во благо. Или не совсем во благо.
Работа с ETW
Event Tracing for Windows собирает и передает сообщения от системных компонентов Windows и сторонних приложений. Появился он еще во времена Windows 2000, но если в те времена системных провайдеров было несколько десятков, то сейчас их счет идет уже на сотни. Сообщения удобно использовать для диагностики ошибок и решения проблем с производительностью софта.
Часть системных провайдеров по умолчанию уже пишет в журнал событий Windows, а часть включается отдельно. Так что даже если вы не знаете про ETW, наверняка им пользуетесь. Познакомиться с журналами и включить часть из них при необходимости можно в стандартном просмотре событий в журналах приложений и служб. Немного о журнале и о работе с ним можно почитать в статье «Вертим логи как хотим ― анализ журналов в системах Windows».
Посмотреть список существующих провайдеров, которые только и рады поведать нам, что с ними происходит, можно командой logman query providers.
Посмотреть список провайдеров, которые подключены к определенному процессу Windows (а значит, и узнать что-то про него), можно при помощи команды logman query providers -pid
Список провайдеров, подключенных к обычному блокноту.
Подписку на события определенного провайдера или на трассировку можно включить через PowerShell при помощи командлета New-NetEventSession. А можно и вовсе накликать мышкой по пути «Управление компьютером» — «Производительность» — «Группы сборщиков данных». Здесь в сеансах отслеживания событий видно, какие трассировки запущены, и при желании можно создать свой сборщик.
Просматривать результат можно при помощи утилит и наборов утилит типа Microsoft Message Analyzer, Windows Performance Toolkit или вовсе командлетом PowerShell Get-WinEvent.
С особенностями работы ETW я рекомендую ознакомиться в документации Microsoft, начать можно с раздела About Event Tracing. Также могу порекомендовать неплохой материал «Изучаем ETW и извлекаем профиты».
Поскольку ETW работает на уровне ядра, то его отличает скорость передачи сообщений и отсутствие необходимости устанавливать какие-либо драйверы или инжекты в приложения. Обычно ETW используют для диагностики производительности и проблем с приложениями. Например, в статье «Ускорение загрузки Windows for fun and profit» анализируются факторы, влияющие на замедление загрузки, а в материале 24-core CPU and I can’t move my mouse — причины торможения Windows на рядовых операциях. Приведу пример — анализ запуска командлетов PowerShell.
Следим за PowerShell
Предположим, что вы каким-то образом (например, через аудит запуска процессов) обнаружили, что на компьютере запускаются невнятные процессы и скрипты PowerShell. Одной из методик будет использование ETW для анализа их активности. Например, посмотрим на провайдера PowerShell. Включим трассировку командой:
Теперь подождем, пока непонятные скрипты отработают, остановим трассировку командой:
Теперь можно посмотреть трассировку, например, через Microsoft Message Analyzer.
Подозрительный clean.ps1 явно что-то ищет и удаляет.
Если выбрать нужную строку, то в нижней панели будет расширенная информация о событии.
А, это же скрипт для очистки кэша 1С!
В этот раз все оказалось банально. Но в более сложных случаях можно запустить трассировку и для проверки других активностей:
- сетевая активность;
- разрешение DNS;
- обращение к диску;
- работа с памятью;
- активность WMI;
- и многое другое.
Таким образом, ETW может помочь поймать зловреда и разобраться в работе приложений. Местами это информативнее, чем привычный Process Monitor. Но помимо дел добрых, у механизма есть и «темная» сторона.
Разумеется, и молотком можно убить, и ружьем спасти. Моральную оценку механизмов делать я, конечно же, не буду, но в любом случае возможности открываются интересные.
Приведу пару примеров в качестве Proof-of-Concept
S — значит бееезопасно
В этом примере я покажу, как легко узнать, что же ищет пользователь в интернете, даже по HTTPS. Посмотреть можно и без PowerShell — только мышка, только хардкор. В нашей задаче будет пользователь, будет Windows, Internet Explorer и журнал событий.
Начнем с того, что включим журнал событий Wininet. Делается это так: открываем журнал событий, на вкладке «Вид» включаем отображение аналитических и отладочных журналов.
Добавляем отображение нужных журналов.
После этого включаем UsageLog в контекстном меню, и этого достаточно для получения нужной информации. Попользуемся IE и посмотрим лог:
Собственно, в журнале видны заголовки и непосредственный запрос в поисковую систему.
Помимо заголовков при помощи журнала можно вытащить и cookie, а заодно посмотреть POST-запросы — например, для вытаскивания учетных данных. Методика работает на любых приложениях, использующих wininet.dll для работы с интернетом. К примеру, браузер Edge.
То же самое запросто реализуется и на PowerShell, и даже на cmd. Приведу пример реализации последним.
Для начала создадим трассировку:
Теперь поработаем в браузере, проверим почту. Трассировку можно после этого остановить командой:
Простейший анализ можно провести при помощи командной утилиты wevtutil.exe. Например, для просмотра POST-запросов команда будет такой:
Можно даже наудачу попробовать поискать по слову password и получить результат.
Пароли открытым текстом. Очень напрягает.
Стоит отметить, что антивирус при этом молчал. Действительно, ведь это обычный процесс трассировки.
Разумеется, события WinInet можно использовать и для диагностики неполадок вроде «почему этот сайт не открывается и что вообще происходит». Но тем не менее, возможности довольно интересны. Перейду к еще более закрученному примеру.
Кейлоггер на PowerShell. Потому что могу.
В Windows есть два интересных провайдера ETW:
Microsoft-Windows-USB-UCX (36DA592D-E43A-4E28-AF6F-4BC57C5A11E8) — работает с USB 2.0.
Microsoft-Windows-USB-USBPORT (C88A4EF5-D048-4013-9408-E04B7DB2814A) — работает с USB 3.0.
С их помощью можно получить данные HID, которые передает такое устройство USB, как клавиатура или мышь. Данные захватываются в сыром виде, но благодаря спецификации HID их вполне можно привести к читаемому виду.
Для начала трассировки достаточно выполнить следующие команды:
А данные можно получить командлетом PowerShell:
Приведу пример простого скрипта, который читает данные трассировки и преображает их в читаемые значения. Преобразование делается только для английских букв и исключительно в заглавные.
При запуске скрипт включает трассировку на 10 секунд, затем показывает результат.
Результат работы скрипта.
Конечно же, разобравшись с данными HID, можно доработать скрипт до полноценного кейлоггера, который записывал бы данные с клавиатуры и мыши. Стоит отметить и ограничения этого механизма:
- работает только с USB, а PS\2 (как порой встречается в ноутбуках) не поддерживается;
- поддержка USB 3.0 заявлена только в Windows 8 и выше;
- требуются права администратора (UAC).
Зато никаких драйверов и перехватчиков. Ну, и конечно, помимо зловредного использования такой кейлоггер может помочь в диагностике проблем с клавиатурой. Теоретически.
Нужно ли бояться
Даже встроенные механизмы в руках злодея могут натворить бед. Методы защиты остаются те же самые: блокировать исполняемые файлы не из системных каталогов, не работать под пользователем с правами администратора, а если и работать — то хотя бы не отключать UAC. И, конечно же, встроенные браузеры Windows по части безопасности вызывают вопросы.
Solving Windows Log Collection Challenges with Event Tracing
Event Tracing for Windows (ETW) logs kernel, application and other system activity. ETW provides better data and uses less resources. By understanding the key characteristics of ETW, system administrators can make a well informed decision on how to utilize the logs collected via ETW to improve IT Security.
About Event Tracing for Windows
Event Tracing for Windows is a kernel-level tracing facility provided by the operating system and enabled dynamically. It logs kernel, application, and other system events.
Available since Windows 2000, ETW provides more detailed information on the operating system environment and application interaction than other logging services on Windows. In addition, ETW does this with less overhead and higher efficiency.
The architecture of ETW is straightforward, an event provider (any user-mode application, managed application or driver) writes events to ETW sessions. When events are written, ETW adds supplementary information about the event time, the process and thread ID that generated the event, the processor ID and the CPU usage data of the logging thread. This information is then ingested by event consumers, either from log files and/or by listening to tracing sessions in real time. Consumers then continue with any other configured processing activities.
The following three, independently functioning component types determine what is logged, when it is logged and where the log events are collected, all with relatively little system overhead. Together these components define an event tracing session.
Controllers enable providers to log events to a session. They start, stop and define event trace sessions as well as specify the session/log file name, location, type and define the way of resolving date-time stamps.
Providers are applications equipped with event tracing instrumentation. When they are enabled by a controller, they send log events to a consumer.
Consumers consume events from one or more event tracing sessions and retrieve events stored in log files along with logs from other real-time sessions. In this context, the log collector(s) act as consumers, ingesting generated events from enabled providers.
Apart from regular event tracing sessions, special purpose tracing sessions are also available, such as Private Logger, System Trace, NT Kernel Logger, AutoLogger and Global Logger. These sessions have predefined data and location settings and often provide the only way to access certain data, such as when events are created early in the boot process of a system.
The Event Trace Data
ETW events include rich metadata, localizable message strings and schematized data payloads. They can be read from memory or saved to a file after decoding it on the source system. The Event Trace Log (ETL) file has a binary format and its content must also be decoded for viewing. Windows provides a GUI (Event Viewer), and a command line utility ( tracerpt ) for this purpose as well as other event tracing tools such as logman .
Below is an excerpt from an example of an event trace in XML format, exported from an ETL file.
The Advantages of ETW
ETW has matured enough to become a well established and useful technology by now. Below are some of the key points in favor of ETW.
ETW provides more thorough, more detailed and more timely data than its log management predecessors on Windows. Since the release of Windows Vista, Windows Event Log and ETW use the same API to log events, allowing administrators to directly access data previously collected via Event Logging and to data that was previously unavailable.
For example: the Microsoft-Windows-PowerShell ETW Provider records which command was run as part of its payload, whereas Windows Event Log merely shows that PowerShell was invoked.
Often, ETW is the only way to access certain log data. DNS logs, for instance, are captured from the Microsoft-Windows-DNSServer ETW provider by enabling Analytical Logging. This is the preferred method for collecting logs from Windows Server versions 2012 R2 (with hotfix 2956577) and later, but this method is not available in earlier versions of Windows Server.
Consumes Less System Resources
ETW uses kernel-level providers and manages memory buffers per session, consuming, as a rule, considerably fewer resources than other logging technologies on Windows, which is especially important when deployed in production environments.
Built up of Independent Components
ETW allows the dynamic updating of sessions and as the components (controllers, providers and consumers) function independently, they can be stopped, started and updated without rebooting the system or restarting the application(s) of interest. Troubleshooting live environments is practically unthinkable without the flexibility it enables.
The Challenges of ETW
There are all good reasons to use ETW, but it also introduces some challenges for system administrators to consider.
ETW has undergone substantial changes with each major release since its introduction in 2000.
The updates added new functions and data structures, typically available only in the updated version of the operating system. An excellent example for this is the format of log files: the original Managed Object Format (MOF) was mostly superseded by the Trace Message Format (TMF), which in turn gave way to the manifest-based XML format. Some earlier components even required a separate PDB (program debugging database) to decode events. The newest format, TraceLogging (TL), was introduced with Windows 10 and embeds decoding information with the recorded log data.
It is clear that managing log collection across multiple file formats increases the overhead on system administrators.
During the lifespan of ETW, tools for collecting, inspecting, analyzing and processing event tracing data have proliferated to keep up with the evolving functional and structural changes introduced.
Finding a solution to structure and centralize the data used by these tools is a must to enable the execution of security analysis tasks such as pattern matching and correlation. However, due to the limited GUI availability and inconsistent CLI tooling options, the burden of managing ETW data can quickly become time-consuming and expensive.
ETW is a «best effort» framework and does not guarantee that all events are captured. Any factor, that could potentially reduce the logging performance of a given system, such as the availability of memory and reduced storage responsiveness is a potential source of problem for reliably capturing event traces.
ETW in Real World Threat Hunting
Administrators are already aware, that attack tactics to cover malicious tracks, such as the Windows Event Log being cleared, will emit its own telemetry in the form of additional Event IDs. By knowing this, administrators are proactively monitoring and alerting for these Event IDs. However, these tactics can fall short if attackers start tampering with ETW, as it can be used as a mechanism to interfere with the flow of logging.
A technique covered by Palantir involves the removing of an ETW Provider from a trace session. As a result, the targeted Event Log is no longer supplied with the correct system telemetry. For administrators, that are reliant on Windows Event Log-based threat detection only, this trick will likely to go unnoticed.
There are a few options to mitigate the effects of tampering with ETW, as this technique can be detected early, if there is a centralized log collection strategy in place to collect logs from the relevant ETW Provider. By collecting event traces with the NXLog Event Tracing for Windows (im_etw) module, administrators can collect and forward traces to a third party suite, such as a SIEM, for further monitoring and incident response.
Other cases where ETW is utilized for attack detection and defense operations include Domain Name System (DNS) log collection to help mitigate attacks involving DNS. Collecting ETW traces also further informs threat detection and operational support in collecting telemetry from critical applications such as Windows Firewall.
Using NXLog as a Single Agent Solution to Collect ETW Logs
To harvest the benefits and overcome the challenges of working with ETW, a single log collection agent is required that poses the following:
Act both as a Controller and Consumer, therefore being able to start the tracing session and collect events directly from the Consumer.
Capable of collecting ETW trace data and then forward it without saving the data to disk, and is able to do it with high efficiency.
Incorporates the technology to enrich the raw data once ETW data is collected, by being able to parse, format and convert the logs for further processing.
Includes the mechanisms to forward the enriched raw data to the required nodes by helping to ease system disk load, in order to avoid the losing of event traces due to the inability to write and process all traces that are being generated.
NXLog does it all using configurable modules.
There are solutions that rely on Microsoft provided tools to capture the ETW trace to disk before decoding the trace file into a human readable format for further processing and analysis. These methods are inefficient and unreliable as they consume system resources in both the storage requirements capturing the trace to disk and in processing or decoding the trace file.
The Event Tracing for Windows (im_etw) module in the NXLog Enterprise Edition allows administrators to use just one log collection software for all their ETW log collection requirements. The agent will collect ETW data at the source, then further parse, format, and forward the data as needed.
With structured log enrichment and centralized log collection, administrators can easily correlate data, create patterns and visualize event data provided by the sources. They can utilize their already established infrastructure such as SIEMs, log management suites, and other dashboards — for data analysis, reporting, alerting, and incident response based on the insights provided by NXLog.
NXLog Ltd. develops multi-platform log collection tools that support many different log sources, formats, transports, and integrations. The tools help administrators collect, parse, and forward logs so they can more easily respond to security issues, investigate operational problems, and analyze event data. NXLog distributes the free and open source NXLog Community Edition and offers additional features and support with the NXLog Enterprise Edition.
This document is provided for informational purposes only and is subject to change without notice. Trademarks are the properties of their respective owners.