- Export corrupts Windows Event Log files
- Introduction
- The problem
- File format
- Export: sorting and renumbering
- The problem
- Bottom line
- Comparison of popular tools
- Экспорт, настройка и просмотр записей журнала аудита Export, configure, and view audit log records
- Шаг 1. Экспорт результатов поиска журнала аудита Step 1: Export audit log search results
- Шаг 2. Формат экспортируемой журнал аудита с помощью редактора power query Step 2: Format the exported audit log using the Power Query Editor
- Использование PowerShell для поиска и экспорта записей журналов аудита Use PowerShell to search and export audit log records
- Советы по экспорту и просмотру журнала аудита Tips for exporting and viewing the audit log
Export corrupts Windows Event Log files
Exported .evtx files may contain corrupted data – Check interpretation of forensic tools.
Author: Jeffrey Wassenaar
Introduction
As forensic investigators, we truly love log files. During the investigation of a system with a Microsoft Windows operating system, Windows Event Log files (.evtx) can be very useful. System events (such as logons) are logged, but applications also tend to save event records in such files. A lot of research has been done since the introduction of the .evtx files in Windows [1], and since then, several tools have been developed to extract and analyze event records.
During our forensic analysis in the field, we have discovered anomalies in certain Windows Event Log files. Research and analysis of these specific anomalies have led to findings that may be of forensic importance for investigators doing similar work. This blogpost will shed a light on the anomalies and the way in which these have been introduced. Subsequently, this blogpost will describe recommendations on how to ensure that the conclusions you draw from forensic analysis of records from Windows Event Log files are actually correct and solid.
The problem
Depending on the scenario of your forensic investigation or incident response case, Windows Event Log files are either extracted from disk images, or may be extracted from a live system. Some first responders or system administrators may be tempted to use the tooling of the Microsoft Windows operating system to export and save event log files from a live system. When they do (using either wevtutil [2] or Windows Event Viewer itself), anomalies are introduced. Depending on which forensic investigation tool you use, the anomalies may lead to incorrect analysis findings and conclusions. To understand what is going on, let’s take a look at the Windows Event Log file format.
File format
A Windows Event Log file starts with a file header, and is followed by several chunks. The file header contains information about the amount of chunks, IDs of the first and last chunk, etc. A file chunk starts with a chunk header, and is followed by event records. The chunk header contains information about the number of records, IDs of the first and last record in this chunk, etc. An event record contains a record header and is followed by the record data. The record header contains information about the record size, a record ID, a timestamp, etc. The actual record is formatted as a binary XML structure in which the actual event record data fields are stored.
Image 1: Simplified diagram of the Windows Event Log file structure
A common configuration of Windows Event logging sets a limit on the file size of a log file. After the first initialization of an event log file, the log file will continue to expand as events are added. When the maximum file size is reached, the oldest information will be overwritten with the most recent log records (a roll-over). To do so, the file chunk containing the oldest information is identified. This file chunk in the file will then be used to store the new log records. This means that the oldest information of a Windows Event Log file may actually reside in the middle of the file.
Image 2: Record IDs in log file with rollover
All event log records contain a (sequential) record ID and a timestamp that describes when the record was created. The record header of each record also contains a record ID and a timestamp. When new records are written to the event log file, the same record ID and timestamp are written to both the header as well as to the record content.
Export: sorting and renumbering
When wevtutil or Windows Event Viewer is used to export the contents of an event log file to an .evtx file, a new file is created. Within this new file, a file header is created, and new chunks are added to it. The oldest event record from the source is identified, and written as the first record in the export .evtx. After the export is complete, the new event log file will be completely sequential in terms of record IDs and will end with the most recent record. Nothing wrong with a bit of sorting, right?
Image 3: Record IDs after export of log file with rollover
While exporting, all actual record data is left intact. However, the record headers are rewritten. During the export, the oldest record will be numbered as record ID 1 in the record header. This means that for an event log that had rolled over before an export, record IDs in the record headers will be changed. In these cases, since the actual record content is left intact, a mismatch between record ID of the header and the record ID inside the record is introduced. That has not proven to be a real problem though.
The problem
While rewriting headers, the wevtutil tool (which is actually also used when using Event Viewer to export files) also rewrites the timestamps of the record headers. For some reason (bug or feature), the timestamp of record 2 is written to the header of record 1. In a similar way, the timestamp of record 3 is written to the header of record 2. At the end of the file, because there is no following record to take a timestamp from, the timestamp inside the header of the last record is set to 0. This means that all event records until the last one are post-dated. Depending on the frequency of the generated events, the amount of time difference in post-dating header timestamps may range from microseconds to even days.
Image 4: Record IDs and timestamps after export
The post-dating in record header timestamps may not be a problem though. After all, the actual record data is left unchanged. Bad news: some tools use timestamps from record headers, instead of those from the actual record data.
The following picture shows the output from a small test script (which uses the python-evtx library [3] from William Ballenthin) of a file exported using wevtutil, and the same file extracted from the disk image. The output shows the timestamp and record ID from both the header as well as from the content of records. The data from the three oldest and the three most recent records are shown.
Image 5: Original data: record content on the left, record headers on the right.
Image 6: Data after export with wevtutil: record content on the left, record headers on the right.
Note that in the data that was exported using wevtutil, there is a mismatch in timestamp data between record headers and record content. Also note the invalid timestamp in the record header of the most recent record.
Bottom line
Check the source of the event log files you examine and make sure that you understand which timestamps are shown by the tooling of your choice. Interpretation of the timestamp from event log record headers may lead to a difference ranging from microseconds up to days. In the end, the misinterpretation of evidence may put an innocent man in jail, or a criminal out on the street.
Comparison of popular tools
The following table lists a couple of popular tools for the analysis of Windows Event Log, and shows which timestamp (from record content, from record header or both) is shown.
When using python-evtx (v0.6.1), Plaso (plaso-20190531) or libevtx (libevtx-20181227) for the analysis of event log records, make sure that timestamps from both the record header as well as from the record content are checked. Microsoft as well as developers of these tools have been notified.
Экспорт, настройка и просмотр записей журнала аудита Export, configure, and view audit log records
После поиска журнала аудита и загрузки результатов поиска в CSV-файл файл содержит столбец AuditData, содержащий дополнительные сведения о каждом событии. After you search the audit log and download the search results to a CSV file, the file contains a column named AuditData, which contains additional information about each event. Данные в этом столбце отформатированы как объект JSON, который содержит несколько свойств, настроенных как свойства:пары значений, разделенные запятой. The data in this column is formatted as a JSON object, which contains multiple properties that are configured as property:value pairs separated by commas. Вы можете использовать функцию преобразования JSON в редакторе запроса питания в Excel, чтобы разделить каждое свойство объекта JSON в столбце AuditData на несколько столбцов, чтобы каждое свойство было иметь свой столбец. You can use the JSON transform feature in the Power Query Editor in Excel to split each property in the JSON object in the AuditData column into multiple columns so that each property has its own column. Это позволяет сортировать и фильтровать одно или несколько этих свойств, что поможет быстро найти определенные данные аудита, которые вы ищете. This lets you sort and filter on one or more of these properties, which can help you quickly locate the specific auditing data you’re looking for.
Шаг 1. Экспорт результатов поиска журнала аудита Step 1: Export audit log search results
Первым шагом является поиск журнала аудита, а затем экспорт результатов в разделенном запятой файле значения (CSV) на локальном компьютере. The first step is to search the audit log and then export the results in a comma-separated value (CSV) file to your local computer.
Запустите поиск журнала аудита и при необходимости пересмотрите критерии поиска до тех пор, пока не будет желаемых результатов. Run an audit log search and revise the search criteria if necessary until you have the desired results.
Нажмите кнопку Экспорт результатов и выберите Скачать все результаты. Click Export results and select Download all results.
Этот параметр экспортирует все записи аудита из поиска журнала аудита, который вы запустили на шаге 1, и загружает необработанные данные из журнала аудита в CSV-файл. This option to exports all the audit records from the audit log search you ran in step 1, and downloads the raw data from the audit log to a CSV file.
В нижней части окна отображается сообщение, которое позволяет открыть или сохранить CSV-файл. A message is displayed at the bottom of the window that prompts you to open or save the CSV file.
Нажмите кнопку Сохранить > сохранить как и сохранить CSV-файл на локальном компьютере. Click Save > Save as and save the CSV file to your local computer. Загрузка многих результатов поиска занимает некоторое время. It takes a while to download many search results. Обычно это происходит при поиске всех действий или широкого диапазона дат. This is typically the case when searching for all activities or a broad date range. Сообщение в нижней части окна отображается при загрузке CSV-файла. A message at the bottom of the windows is displayed when the CSV file is finished downloading.
В CSV-файл можно загрузить до 50 000 записей результатов одной операции поиска по журналу аудита. You can download a maximum of 50,000 entries to a CSV file from a single audit log search. Если в CSV-файл загружено 50 000 записей, можно предположить, что условиям поиска соответствует более 50 000 событий. If 50,000 entries are downloaded to the CSV file, you can probably assume there are more than 50,000 events that met the search criteria. Чтобы экспортировать больше, чем это ограничение, попробуйте использовать диапазон дат, чтобы уменьшить количество записей журналов аудита. To export more than this limit, try using a date range to reduce the number of audit log records. Чтобы экспортировать больше 50 000 записей, вы можете выполнить поиск несколько раз со смежными диапазонами дат. You might have to run multiple searches with smaller date ranges to export more than 50,000 entries.
Шаг 2. Формат экспортируемой журнал аудита с помощью редактора power query Step 2: Format the exported audit log using the Power Query Editor
Следующим шагом является использование функции преобразования JSON в редакторе запроса питания в Excel, чтобы разделить каждое свойство объекта JSON в столбце AuditData на свой столбец. The next step is to use the JSON transform feature in the Power Query Editor in Excel to split each property in the JSON object in the AuditData column into its own column. Затем вы фильтруете столбцы для просмотра записей на основе значений определенных свойств. Then you filter columns to view records based on the values of specific properties. Это поможет вам быстро найти определенные данные аудита, которые вы ищете. This can help you quickly locate the specific auditing data you’re looking for.
Откройте пустую книгу в Excel для Office 365, Excel 2019 или Excel 2016. Open a blank workbook in Excel for Office 365, Excel 2019, or Excel 2016.
На вкладке Data в группе ленты Get & преобразование данных нажмите кнопку Текст/CSV. On the Data tab, in the Get & Transform Data ribbon group, click From Text/CSV.
Откройте файл CSV, загруженный в шаге 1. Open the CSV file that you downloaded in Step 1.
В отображаемом окне щелкните Преобразование данных. In the window that’s displayed, click Transform Data.
Файл CSV открыт в редакторе запроса. The CSV file is opened in the Query Editor. Существует четыре столбца: CreationDate, UserIds, Operations и AuditData. There are four columns: CreationDate, UserIds, Operations, and AuditData. Столбец AuditData — это объект JSON, содержащий несколько свойств. The AuditData column is a JSON object that contains multiple properties. Следующий шаг — создание столбца для каждого свойства объекта JSON. The next step is to create a column for each property in the JSON object.
Щелкните правой кнопкой мыши название в столбце AuditData, щелкните Преобразование и нажмите кнопку JSON. Right-click the title in the AuditData column, click Transform, and then click JSON.
В верхнем правом углу столбца AuditData щелкните значок расширения. In the upper-right corner of the AuditData column, click the expand icon.
Отображается неполный список свойств объектов JSON в столбце AuditData. A partial list of the properties in the JSON objects in the AuditData column is displayed.
Щелкните Загрузить больше, чтобы отобразить все свойства в объектах JSON в столбце AuditData. Click Load more to display all properties in the JSON objects in the AuditData column.
Вы можете отключить почтовый ящик рядом с любым свойством, которое вы не хотите включать. You can unselect the checkbox next to any property that you don’t want to include. Устранение столбцов, которые не являются полезными для вашего расследования, — это хороший способ уменьшить количество данных, отображающихся в журнале аудита. Eliminating columns that aren’t useful for your investigation is a good way to reduce the amount of data displayed in the audit log.
Свойства JSON, отображаемые на предыдущем скриншоте (после нажатия нагрузки больше), основаны на свойствах, найденных в столбце AuditData из первых 1000 строк в CSV-файле. The JSON properties displayed in the previous screenshot (after you click Load more) are based on the properties found in the AuditData column from the first 1,000 rows in the CSV file. Если после первых 1000 строк в записях имеются различные свойства JSON, эти свойства (и соответствующий столбец) не будут включены при разделении столбца AuditData на несколько столбцов. If there are different JSON properties in records after the first 1,000 rows, these properties (and a corresponding column) won’t be included when the AuditData column is split into multiple columns. Чтобы предотвратить это, рассмотрите возможность повторного запуска поиска журнала аудита и сузить критерии поиска, чтобы было возвращено меньше записей. To help prevent this, consider re-running the audit log search and narrow the search criteria so that fewer records are returned. Другим обходным решением является фильтрация элементов в столбце Operations, чтобы уменьшить число строк (перед выполнением шага 5 выше) перед преобразованием объекта JSON в столбце AuditData. Another workaround is to filter items in the Operations column to reduce the number of rows (before you perform step 5 above) before transforming the JSON object in the AuditData column.
Чтобы просмотреть атрибут в списке, например AuditData.AffectedItems, щелкните значок Расширение в правом верхнем углу столбца, из чего нужно вытащить атрибут, а затем выберите Расширение до New Row. To view an attribute within a list such as AuditData.AffectedItems, click the Expand icon in the upper right corner of the column you want to pull an attribute from, and then select Expand to New Row. Оттуда будет запись, и вы можете щелкнуть значок Расширение в верхнем правом углу столбца, просмотреть атрибуты и выбрать тот, который необходимо просмотреть или извлечь. From there it will be a record and you can click the Expand icon in the upper right corner of the column, view the attributes, and select the one you want to view or extract.
Сделайте одно из следующих вещей для формата заголовка столбцов, добавляемого для каждого выбранного свойства JSON. Do one of the following things to format the title of the columns that are added for each JSON property that’s selected.
Отклонйте исходное имя столбца в качестве почтового ящика префикса, чтобы использовать имя свойства JSON в качестве имен столбцов; например, RecordType или SourceFileName. Unselect the Use original column name as prefix checkbox to use the name of the JSON property as the column names; for example, RecordType or SourceFileName.
Оставьте исходное имя столбца в качестве почтового ящика префикса, выбранного для добавления префикса AuditData в имена столбцов; например, AuditData.RecordType или AuditData.SourceFileName. Leave the Use original column name as prefix checkbox selected to add the AuditData prefix to the column names; for example, AuditData.RecordType or AuditData.SourceFileName.
Нажмите ОК. Click OK.
Столбец AuditData разделен на несколько столбцов. The AuditData column is split into multiple columns. Каждый новый столбец соответствует свойству объекта AuditData JSON. Each new column corresponds to a property in the AuditData JSON object. Каждая строка в столбце содержит значение свойства. Each row in the column contains the value for the property. Если свойство не содержит значения, отображается значение null. If the property doesn’t contain a value, the null value is displayed. В Excel ячейки со значениями null пусты. In Excel, cells with null values are empty.
На вкладке Главная нажмите кнопку Закрыть &, чтобы закрыть редактор запроса питания и открыть преобразованный CSV-файл в книге Excel. On the Home tab, click Close & Load to close the Power Query Editor and open the transformed CSV file in an Excel workbook.
Использование PowerShell для поиска и экспорта записей журналов аудита Use PowerShell to search and export audit log records
Вместо использования средства поиска журналов аудита в Центре & обеспечения соответствия требованиям можно использовать в Exchange Online PowerShell для экспорта результатов поиска журнала аудита в CSV-файл. Instead of using the audit log search tool in the Security & Compliance Center, you can use the Search-UnifiedAuditLog cmdlet in Exchange Online PowerShell to export the results of an audit log search to a CSV file. Затем вы можете следовать той же процедуре, описанной в шаге 2, чтобы форматирование журнала аудита с помощью редактора Power Query. Then you can follow the same procedure described in Step 2 to format the audit log using the Power Query editor. Одно из преимуществ использования комлета PowerShell заключается в том, что вы можете искать события из определенной службы с помощью параметра RecordType. One advantage of using the PowerShell cmdlet is that you can search for events from a specific service by using the RecordType parameter. Вот несколько примеров использования PowerShell для экспорта записей аудита в CSV-файл, чтобы можно было использовать редактор Power Query для преобразования объекта JSON в столбце AuditData, как описано в шаге 2. Here are few examples of using PowerShell to export audit records to a CSV file so you can use the Power Query editor to transform the JSON object in the AuditData column as described in Step 2.
В этом примере запустите следующие команды, чтобы вернуть все записи, связанные с операциями общего доступа SharePoint. In this example, run the following commands to return all records related to SharePoint sharing operations.
Результаты поиска экспортируются в CSV-файл с именем PowerShellAuditlog, содержащий четыре столбца: CreationDate, UserIds, RecordType, AuditData. The search results are exported to a CSV file named PowerShellAuditlog that contains four columns: CreationDate, UserIds, RecordType, AuditData).
В качестве значения параметра RecordType можно также использовать имя или значение переписи для типа записи. You can also use the name or enum value for the record type as the value for the RecordType parameter. Список имен типов записей и соответствующих значений списка см. в таблице AuditLogRecordType в схеме API управления Office 365. For a list of record type names and their corresponding enum values, see the AuditLogRecordType table in Office 365 Management Activity API schema.
Можно включить только одно значение для параметра RecordType. You can only include a single value for the RecordType parameter. Чтобы найти записи аудита для других типов записей, необходимо выполнить две предыдущие команды, чтобы указать другой тип записи и примедить эти результаты к исходному CSV-файлу. To search for audit records for other record types, you have to run the two previous commands again to specify a different record type and append those results to the original CSV file. Например, вы запустите следующие две команды, чтобы добавить действия файла SharePoint из того же диапазона дат в PowerShellAuditlog.csv файл. For example, you would run the following two commands to add SharePoint file activities from the same date range to the PowerShellAuditlog.csv file.
Советы по экспорту и просмотру журнала аудита Tips for exporting and viewing the audit log
Ниже представлены некоторые советы и примеры экспорта и просмотра журнала аудита до и после использования функции преобразования JSON для разделения столбца AuditData на несколько столбцов. Here are some tips and examples of exporting and viewing the audit log before and after you use the JSON transform feature to split the AuditData column into multiple columns.
Фильтр столбца RecordType для отображения только записей из определенной службы или функциональной области. Filter the RecordType column to display only the records from a specific service or functional area. Например, чтобы показать события, связанные с совместной деятельностью SharePoint, необходимо выбрать 14 (значение enum для записей, запускаемой действиями совместного доступа SharePoint). For example, to show events related to SharePoint sharing, you would select 14 (the enum value for records triggered by SharePoint sharing activities). Список служб, соответствующих значениям списка, отображаемого в столбце RecordType, см. в статье Подробные свойства в журнале аудита. For a list of the services that correspond to the enum values displayed in the RecordType column, see Detailed properties in the audit log.
Фильтр столбца Operations для отображения записей для определенных действий. Filter the Operations column to display the records for specific activities. Список большинства операций, соответствующих поисковой активности в средстве поиска журналов аудита в Центре соответствия требованиям & безопасности, см. в разделе «Аудит действий» в разделе Поиск журнала аудита в Центре соответствия требованиям & безопасности. For a list of most operations that correspond to a searchable activity in the audit log search tool in the Security & Compliance Center, see the «Audited activities» section in Search the audit log in the Security & Compliance Center.