Windows server кто удалил файл

С помощью аудита событий доступа к объектам файловой системы вы можете определить конкретного пользователя, который создал, удалил или изменил определенный файл. В этой статье мы покажем, как настроить аудит событий удаления объектов в общей сетевой папке на Windows Server 2016. После настройки аудита, вы можете с помощью информации в журнале событий найти пользователя, который удалил на файловом сервере.

При удалении файла из сетевой папки, он удаляется сразу, а не отправляется в корзину пользователя. Список открытых по сети файлов в сетевой папке можно получить так.

Содержание:

  • Включаем политику аудита доступа к файлам и папкам в Windows
  • Настройка аудита событий удаления файлов из конкретной папки
  • Запись событий удаления файлов в SQL базу (MySQL/MSSQL)
  • Запись информации о событиях удаления файлов в текстовый файл

Включаем политику аудита доступа к файлам и папкам в Windows

По умолчанию в Windows Server не включен аудит событий доступа к объектам на файловой системе. Вы можете включить и настроить аудит событий с помощью групповой политики. Если нужно включить политики аудита на нескольких серверах или компьютера, можно использовать доменные GPO (настраиваются с помощью консоли управления gpmc.msc). Если нужно настроить аудит только на одном сервере, можно воспользоваться локальной групповой политикой.

  1. Запустите консоль редактора локальной политики –
    gpedit.msc
    ;
  2. Перейдитевраздел GPO срасширенными политиками аудита Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> Object Access;
  3. Откройте политику Audit File System и укажите, что вы хотите сохранять в журнал только успешные события доступа к объектам файловой системы (Configure the following audit events -> Success);

    Также можно включить аудит доступа к локальным объектам с помощью политики Audit Object Access в разделе Windows Settings -> Security Settings -> Local Policy -> Audit Policy. Однако использование политики Audit File System предпочтительнее, поскольку она отслеживает только события NTFS.

    включить политику аудита доступа к сетевым папкам в windows server

  4. Сохраните изменения и обновите настройки локальной групповой политики с помощью команды
    gpupdate /force
    .

Настройка аудита событий удаления файлов из конкретной папки

Теперь нужно настроить аудит в свойствах общей сетевой папки, доступ к которой вы хотите отслеживать. Запустите проводник и откройте свойства общей папки. Перейдите на вкладку Security. Нажмите кнопку Advanced -> вкладка Auditing.

Если появится сообщение You must be an administrator or have been given the appropriate privileges to view the audit properties of this object, нажмите кнопку Continue.

настройка аудита доступа к сетевой папке в windows

Затем нажмите кнопку Add чтобы указать пользователя или группу, для которых нужно записывать все события аудита. Если вы хотите отслеживать события для всех пользователей, укажите группу Everyone.

Затем нужно указать использование каких разрешений доступа к объекту нужно записывать в лог. Чтобы сохранять в Event Log только события удаления файлов, нажмите кнопку Show advanced permissions. В списке событий оставьте аудит только для событий удаления папок и файлов — Delete и Delete subfolders and files.

Совет. Включение аудита доступа к объектам Windows накладывает дополнительные расходы на ресурсы системы. Всегда старайтесь минимизировать количество объектов и событий аудита, которые нужно отслеживать.

отслеживание удаления файлов в сетевой папке

Совет. Вы можете настроить аудит удаления файлов в папке с помощью через PowerShell:

$Path = "D:\Public"
$AuditChangesRules = New-Object System.Security.AccessControl.FileSystemAuditRule('Everyone', 'Delete,DeleteSubdirectoriesAndFiles', 'none', 'none', 'Success')
$Acl = Get-Acl -Path $Path
$Acl.AddAuditRule($AuditChangesRules)
Set-Acl -Path $Path -AclObject $Acl

Теперь, если пользователь удалит любой файл или папку в сетевой папке, в журнале безопасности системы появляется событие File System -> Audit Succes c Event ID 4663 от источника Microsoft Windows security auditing.

Откройте mmc консоль Event Viewer (
eventvwr.msc
), разверните секцию Windows Logs -> Security. Включите фильтр событий по EventID 4663.

событие с кодом 4663 - удаление файла

Откройте любой их оставшихся событий в Event Viewer. Как вы видите, в нем есть информация об имени удаленного файла и учетной записи пользователя, который удалил файл.

An attempt was made to access an object.
Subject:
Security ID:                            CORP\aaivanov
Account Name:                     aaivanov
 Account Domain:                  CORP
Logon ID:                               0x61B71716
Object:
Object Server:                        Security
Object Type:                          File
Object Name:                        E:\Distr\Backup.rar
Handle ID:                              0x7bc4
Resource Attributes:            S:AI
Process Information:
Process ID:                             0x4
Process Name:
Access Request Information:
Accesses:                               DELETE
Access Mask:                         0x10000

кто удалил общий файл в сетевой папке

После настройки аудита, найдите в журнале Security вы сможете найти с:

  • Кто и когда удалил файл в сетевой папке;
  • Из какого приложения удален файл;
  • На какой момент времени нужно восстанавливать бэкап данного каталога.

Запись событий удаления файлов в SQL базу (MySQL/MSSQL)

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

Вы можете записывать все нужные событий в отдельную SQL базу данных. Для хранения событий можно использовать Microsoft SQL Server, Elasticsearch или MySQL/MariaDB.

В этом примере мы покажем, как записывать события аудита в отдельную таблицу БД на сервере MySQL. Формат таблицы:

  • Имя сервера;
  • Имя удаленного файла
  • Время удаления;
  • Имя пользователя, удалившего файл.

MySQL запрос на создание такой таблицы будет выглядеть так:

CREATE TABLE track_del (id INT NOT NULL AUTO_INCREMENT, server VARCHAR(100), file_name VARCHAR(255), dt_time  DATETIME, user_name VARCHAR(100),  PRIMARY KEY (ID));

Для получения событий с EventID 4663 из журнала Security за текущий день можно использовать такой PowerShell скрипт:

$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName="Security";starttime="$today";id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat "%Y-%m-%d %H:%M:%S"
$File = $event.Event.EventData.Data[6]."#text"
$User = $event.Event.EventData.Data[1]."#text"
$Computer = $event.Event.System.computer
}
}

Имеющиеся данные в событии удаления файла

Следующий PowerShell скрипт запишет полученные данные в БД MySQL на удаленном сервере:

Set-ExecutionPolicy RemoteSigned
Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll'
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString='server=10.7.7.13;uid=posh;pwd=P@ssw0rd;database=aduser'}
$Connection.Open()
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = $Connection
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName="Security";starttime="$today";id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat "%Y-%m-%d %H:%M:%S"
$File = $event.Event.EventData.Data[6]."#text"

$File = $File.Replace(‘\’,’|’)
$User = $event.Event.EventData.Data[1]."#text"
$Computer = $event.Event.System.computer
$sql.CommandText = "INSERT INTO track_del  (server,file_name,dt_time,user_name ) VALUES ('$Computer','$File','$Time','$User')"
$sql.ExecuteNonQuery()
}
}
$Reader.Close()
$Connection.Close()

После сохранения событий во внешнюю базу данных, этот журнал можно очистить.

Теперь, чтобы узнать, кто удалил файл «document1 — Copy.DOC». Достаточно в консоли PowerShell выполнить следующий скрипт.

$DeletedFile = "%document1 - Copy.DOC%"
Set-ExecutionPolicy RemoteSigned
Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll'
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString='server=10.7.7.13;uid=posh;pwd=P@ssw0rd;database=aduser'}
$Connection.Open()
$MYSQLCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter
$MYSQLDataSet = New-Object System.Data.DataSet
$MYSQLCommand.Connection=$Connection
$MYSQLCommand.CommandText="SELECT user_name,dt_time    from  track_del where file_name LIKE '$DeletedFile'"
$MYSQLDataAdapter.SelectCommand=$MYSQLCommand
$NumberOfDataSets=$MYSQLDataAdapter.Fill($MYSQLDataSet, "data")
foreach($DataSet in $MYSQLDataSet.tables[0])
{
write-host "User:" $DataSet.user_name "at:" $DataSet.dt_time
}
$Connection.Close()

В результате в консоли PS появится имя пользователя и время удаления файла.

Запрос PowerShell к mysql БД для получении инфомации о пользователе, удалившем файл

Примечание. Была обнаружена проблема — символ «\» не записывается в БД, поэтому мы заменили его на «|». Соответственно если нужно вывести полный путь к файлу, при выборке из базы можно выполнить обратную замену:
$DataSet.file_name.Replace(‘|’,’\’)
. Спасибо Alex Kornev за замечание!

Скрипт сброса данных из журнала в БД можно выполнять один раз в конце дня по планировщику или повесить триггер на событие удаления (On Event), что более ресурсоемко. Все зависит от требования к системе.

Совет. Нужно убедиться, что вы указали достаточно большой максимальный размер для журнала безопасности, чтобы в него помещались все события за день. Иначе придется запускать задания сброса данных из журнала в базу чаще, чем 1 раз в день, или вообще по триггеру. Для рабочих станция Maximum Log Size как правило стоит задать не менее 64 Мб, на северах – 262 Мб. Опцию перезаписи старых событий нужно оставить включенной (Overwrite events as needed).

Можно создать реагировать простую веб страницу на php для получения информации о событиях удаления файлов в более удобном виде. Задача решается силами любого php программиста за 1-2 часа.

Важный совет. При наличии в журнале информации об удалении файла пользователем не спешите однозначно интерпретировать его как преднамеренное или даже злонамеренное. Многие программы (особенно этим грешат программы пакета MS Office), при сохранении изменений, сначала создается временный файл, данные записываются в него, а старая версия файла удаляется. В этом случае имеет смысл дополнительной записи в БД имени процесса, которым было выполнено удаление файла (поле ProcessName события), и вести анализ событий удаления файлов с учетом этого факта. Либо можно фильтровать события от некоторых процессов, например, winword.exe, excel.exe и пр.

Запись информации о событиях удаления файлов в текстовый файл

Если вы не хотите вести отдельную БД, можно сохранять события аудита удалений файлов в текстовый лог файл. Воспользуйтесь таким PowerShell скриптом:

$Outfile = "C:\ps\delete-file-log.txt"
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName="Security";starttime="$today";id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat "%Y-%m-%d %H:%M:%S"
$File = $event.Event.EventData.Data[6]."#text"
$User = $event.Event.EventData.Data[1]."#text"
$strLog = $Computer + " " + $File + " " +  $Time + " " +  $User
$strLog  | out-file $Outfile –append
}
}

лог со списком удаленных файлов в windows

[/alert]

Итак, мы предложили идею и некий общий каркас системы аудита и хранения информации об удаленных файлах в сетевых шарах, при желании ее с лёгкостью можно будет модифицировать под ваши нужды.

Иногда бывает необходимо понять кто удалил/изменил/переименовал конкретный файл или папку. В ОС Windows для этого используется аудит доступа к объектам.

Аудит — это запись в специальные журналы информации об определенных событиях (источник, код события, успешность, объект и т.д. ). Объектом аудита может являться как любой файл или папка, так и определенное событие, например вход в систему или выход из нее, то есть можно записывать все события происходящие с конкретным файлом или папкой — чтение, запись, удаление и т.д., можно события входа в систему и т.д.

Необходимо понимать, что аудит забирает на себя.

Для того, чтобы можно было настраивать аудит файлов и папок необходимо предварительно включить эту возможность через локальные (или в случае если у Вас используется Microsoft AD групповые) политики безопасности.

В случае локальных политик необходимо запустить оснастку “Локальная политика безопасности”, для этого необходимо нажать комбинацию клавиш Win+R, в открывшееся поле ввести secpol.msc и нажать клавишу Enter.

Запуск локальной политики безопасности

В открывшейся оснастке в дереве слева необходимо перейти в раздел “Локальные политики” — “Политика аудита”.

Политика аудита

Далее необходимо выбрать необходимую нам политику — в данном случае это “Аудит доступа к объектам”. Именно этой политикой регулируется доступ к объектам файловой системы (файлам и папкам) и раскрыть ее двойным щелчком мыши. В открывшемся окне необходимо выбрать какие именно типы событий будут регистрироваться — “Успех” (разрешение на операцию получено) и/или “Отказ” — запрет операции и проставить соответствующие галочки, после чего нажать “Ок”.

Выбор политики

Теперь когда включена возможность ведения аудита интересующих нас событий и их тип можно переходить к настройке самих объектов — в нашем случае файлов и папок.

Для этого необходимо открыть свойства файла или папки, перейти на вкладку “Безопасность”, нажать “Дополнительно” и “Аудит”.

Аудит

Нажимаем “Добавить” и начинаем настраивать аудит.

Настройка аудита

Сначала выбираем субъект — это чьи действия будут аудироваться (записываться в журнал аудита).

Выбор субъекта

Можно вписать туда имя пользователя или группы, если имя заранее неизвестно, то можно воспользоваться кнопкой “Дополнительно” которая открывает форму поиска где можно выбрать интересующих нас пользователей и группы. Чтобы контролировались действия всех пользователей необходимо выбрать группу “Все”.

Пользовательские группы

Далее необходимо настроить тип аудируемых событий (Успех, Отказ, Все), также область область применения для аудита папок — только эта папка, папка с подпапками, только подпапки. только файлы и т.д., а также сами события аудита.

Для папок поля такие:

Типы событий для папок

А такие для файлов:

Типы событий для файлов

После этого начнется сбор данных аудита. Все события аудита пишутся в журнал “Безопасность”. Открыть его проще всего через оснастку “Управление компьютером” compmgmt.msc.

Сбор данных аудита

В дереве слева выбрать “Просмотр событий” — “Журналы Windows” — “Безопасность”.

Просмотр событий

Каждое событие ОС Windows имеет свой код события. Список событий достаточно обширен и доступен на сайте Microsoft либо в интернете.

Попробуем например найти событие удаления файла, для этого удалим файл на котором предварительно настроен аудит (если это не тестовые файл, то не забываем сделать его копию, так как аудит это всего лишь информация о действиях, а не разрешение/запрет этих действий). Нам нужно событие с кодом 4663 — получение доступа к объекту, у которого в поле Операции доступа Написано “DELETE” . Поиск событий в журналах Windows достаточно сложен, поэтому обычно используются специализированные средства анализа — системы мониторинга, скрипты и т.д.

Вручную можно, например, задать например такой фильтр:

Фильтры

Далее в отфильтрованных событиях необходимо найти интересующее нас по имени объекта.

Поиск нужного объекта

Открыть его двойным щелчком мыши и увидеть кто удалил данный файл в поле субъект.

Информация о файле

На этом демонстрация аудита доступа к файлам и папкам Windows на примере Windows server 2012R2 окончена. В нашей базе знаний вы найдёте ещё множество статей посвящённых различным аспектам работы в Windows, а если вы ищете надежный виртуальный сервер под управлением Windows, обратите внимания на нашу услугу — Аренда виртуального сервера Windows.

 

Still not sure how to track who deleted file/folder from windows server 2016 with audit policy? Take a look at this blog.

Here at Bobcares, we have seen several such Windows-related errors as part of our Server Management Services for web hosts and online service providers.

Today we’ll see how to track the deleted file/folder Windows.

How to track Who Deleted File/Folder from Windows Server 2016 with Audit Policy

Now let’s take a look at how our Support Engineers find who deleted the file/folder from the server.

We make use of the file system object access event auditing to identify a specific user who created, deleted, or modified a specific file.

We shall now see how to configure event auditing for files on a shared network folder on Windows Server 2016. After configuring auditing, we use the information from the Event Viewer to find the user who deleted a specific file on the file server.

However, when we delete a file from a shared network folder, it is deleted immediately instead of being sent to the user’s recycle bin.

How to Enable File and Folder Access Auditing Policy on Windows

By default, the File System Object Access audit won’t be enabled on Windows Server. We can enable and configure audit settings using Group Policy. Here are the steps that we follow to configure auditing on one server by using the Local Group Policy Editor.

    • First, we open the Local Group Policy Editor console – gpedit.msc
    • Next, we go to the GPO section with advanced audit policies: Windows Settings >> Security Settings >> Advanced Audit Policy Configuration >> Object Access
    • After that, we open the Audit File System policy and specify that we want to log only successful access events to file system objects (Configure the following audit events >> Success)
      how to track who deleted file/folder from windows server 2016 with audit policy

    • Finally, we save the changes and update the local Group Policy settings using the below command.
      gpupdate /force

Configuring File Deleted Audit Settings on a Shared Folder

Now we configure auditing in the properties of the share network folder to which we want to track access.

1. First, we run File Explorer and open the folder properties. We go to the Security tab and click the Advanced button. Then we go to the Auditing tab.

2. If the message below message appears, click the Continue button.

You must be an administrator or have been given the appropriate privileges to view the audit properties of this object

3. Then we click the Add button to specify the user or group for which we want to capture audit events. If we want to track access events for all users, we do specify the Everyone group.

4. After that, we also specify which permissions used to access the object should be logged. To save only file deletion events in the Event Log, we click the Show advanced permissions button. In the event list, we leave auditing only for the folder and file deletion events – Delete and Delete subfolders and files.

In case, the user deletes any file or folder in the shared network folder. Then the File System -> Audit Success file delete event appears in the Security log with Event ID 4663 from the Microsoft Windows security auditing source.

Then we open the Event Viewer MMC console (eventvwr.msc), expand the Windows Logs -> Security section. Enable event log filter by the EventID 4663.

After that, we open any of the remaining events in the Event Viewer. We see that it contains information about the name of the deleted file, the account of the user who deleted the file, and the process name.

An attempt was made to access an object.
Subject:Security ID: CORP\jon
Account Name: jon
Account Domain: CORP
Logon ID: 0x32B12627
Object:Object Server: Security
Object Type: File
Object Name: E:\Distr\Backup.rar
Handle ID: 0x7bc4
Resource Attributes: S:AI
Process Information:
Process ID: 0x4
Process Name:
Access Request Information:
Accesses: DELETE
Access Mask: 0x10000

After enabling file access auditing policy, we can find the below details in the Security log:

  • Who deleted the file from the shared network folder and when it happened
  • What application (process) was used to delete the file
  • What is the date of the backup to be restored

How to Write File Deletion Events to SQL Database (MySQL/MSSQL)

However, even if the audit of the deleted files is enabled, it can be troublesome to find something in the logs. Firstly, it is quite hard to find a specific entry among thousands of events. Secondly, if a file was deleted a long time ago, this event may be absent in the logs, since it was overwritten by new events.

We save all file delete events to the SQL database. For that, we use Microsoft SQL Server, Elasticsearch, or MySQL/MariaDB databases to store the events.

For example, let’s see how to log audit events to a separate database table on MySQL. We can use the following table format:

  • Server name
  • Name of the deleted file
  • Date and time
  • Name of the user who has deleted the file

The MySQL query to create this table looks like below:

CREATE TABLE deleted_items (id INT NOT NULL AUTO_INCREMENT, server VARCHAR(100), file_name VARCHAR(255), dt_time DATETIME, user_name VARCHAR(100), PRIMARY KEY (ID));

To get events with EventID 4663 from the Security log for the current day, we use the following PowerShell script:

$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName=”Security”;starttime=”$today”;id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat “%Y-%m-%d %H:%M:%S”
$File = $event.Event.EventData.Data[6].”#text”
$User = $event.Event.EventData.Data[1].”#text”
$Computer = $event.Event.System.computer
}
}

The next PowerShell script will write the data we get to the MySQL database on a remote server (with the IP address 10.1.1.13):

Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll’
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString=’server=10.1.1.13;uid=posh;pwd=P@ssw0rd;database=aduser’}
$Connection.Open()
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = $Connection
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName=”Security”;starttime=”$today”;id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat “%Y-%m-%d %H:%M:%S”
$File = $event.Event.EventData.Data[6].”#text”
$File = $File.Replace(‘\’,’|’)
$User = $event.Event.EventData.Data[1].”#text”
$Computer = $event.Event.System.computer
$sql.CommandText = “INSERT INTO deleted_items (server,file_name,dt_time,user_name ) VALUES (‘$Computer’,’$File’,’$Time’,’$User’)”
$sql.ExecuteNonQuery()
}
}
$Reader.Close()
$Connection.Close()

After saving events to an external database, we can clear this Event log.

Now, to find out who has deleted the file “AnnualReport.DOC“, we run the below script in the PowerShell console.

$DeletedFile = “%AnnualReport.DOC%”
Set-ExecutionPolicy RemoteSigned
Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll’
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString=’server=10.1.1.13;uid=posh;pwd=P@ssw0rd;database=aduser’}
$Connection.Open()
$MYSQLCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter
$MYSQLDataSet = New-Object System.Data.DataSet
$MYSQLCommand.Connection=$Connection
$MYSQLCommand.CommandText=”SELECT user_name,dt_time from deleted_items where file_name LIKE ‘$DeletedFile'”
$MYSQLDataAdapter.SelectCommand=$MYSQLCommand
$NumberOfDataSets=$MYSQLDataAdapter.Fill($MYSQLDataSet, “data”)
foreach($DataSet in $MYSQLDataSet.tables[0])
{
write-host “User:” $DataSet.user_name “at:” $DataSet.dt_time
}
$Connection.Close()

Finally, now, we see the username and the time the file was deleted in the PS console.

Logging File Delete Audit Events to a Text File

If we don’t want to use a separate database server, we save file deletion audit events to a plain text log file. For that, we use this PowerShell script to save the output to a text file:

$Outfile = “C:\Logs\Deleted-file-history-log.txt”
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName=”Security”;starttime=”$today”;id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat “%Y-%m-%d %H:%M:%S”
$File = $event.Event.EventData.Data[6].”#text”
$User = $event.Event.EventData.Data[1].”#text”
$strLog = $Computer + ” ” + $File + ” ” + $Time + ” ” + $User
$strLog | out-file $Outfile –append
}
}

[Need any further assistance in tracking the file/folder deletion queries? – We are here to help you]

Conclusion

Today, we saw how our Support Engineers find out who deleted the file/folder in the Windows server.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

You can use file system object access event auditing to identify a specific user who created, deleted, or modified a specific file. In this article, we’ll show you how to configure event auditing for files on a shared network folder on Windows Server 2016. After configuring auditing, you can use the information from the Event Viewer to find the user who deleted specific file on the file server.

When you delete a file from a shared network folder, it is deleted immediately instead of being sent to the user’s recycle bin. The list of files opened on the shared folder can be obtained as follows.

How to Enable File and Folder Access Auditing Policy on Windows?

By default, File System Object Access audit is not enabled on Windows Server. You can enable and configure audit settings using Group Policy. If you need to enable audit policies on multiple servers or computers, you can use domain GPOs (configurable using the gpmc.msc MMC console). If you only want to configure auditing on one server, you can use Local Group Policy Editor.

  1. Open the Local Group Policy Editor console – gpedit.msc;
  2. Go to the GPO section with advanced audit policies: Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> Object Access;
  3. Open the Audit File System policy and specify that you want to log only successful access events to file system objects (Configure the following audit events -> Success);

    You can also enable auditing of local objects access using the Audit Object Access policy under Windows Settings -> Security Settings -> Local Policy -> Audit Policy. However, using the File System Audit policy is preferable because it only tracks NTFS access events.

    enable audit file system policy on windows server

  4. Save the changes and update your local Group Policy settings using the command: gpupdate /force.

Configuring File Deleted Audit Settings on a Shared Folder

Now you need to configure auditing in the properties of the shared network folder you want to track access to. Run File Explorer and open the folder properties. Go to the Security tab. Click the Advanced button -> go to the Auditing tab.

If the message “You must be an administrator or have been given the appropriate privileges to view the audit properties of this object” appears, click the Continue button.

configure audit settings on a shared folder

Then click the Add button to specify the user or group for which you want to capture audit events. If you want to track access events for all users, specify the Everyone group.

Then you need to specify which permissions used to access the object should be logged. To save only file deletion events in the Event Log, click the Show advanced permissions button. In the event list, leave auditing only for folder and file deletion events – Delete and Delete subfolders and files.

configure audit of file deletion actions on shared folder on Windows Server 2016folder

Tip. Remember that the auditing policy for Windows objects requires additional computing resources. Use it carefully, always try to minimize the number of audit objects and events to log.

$Path = "E:\Public"
$AuditChangesRules = New-Object System.Security.AccessControl.FileSystemAuditRule('Everyone', 'Delete,DeleteSubdirectoriesAndFiles', 'none', 'none', 'Success')
$Acl = Get-Acl -Path $Path
$Acl.AddAuditRule($AuditChangesRules)
Set-Acl -Path $Path -AclObject $Acl

Now, if the user deletes any file or folder in the shared network folder, the File System -> Audit Success file delete event appears in the Security log with Event ID 4663 from the Microsoft Windows security auditing source.

Open the Event Viewer mmc console (eventvwr.msc), expand the Windows Logs -> Security section. Enable event log filter by the EventID 4663.

file deletion event id 4663 in the security log of windows event viewer

Open any of the remaining events in the Event Viewer. As you can see, it contains information about the name of the deleted file, the account of the user who deleted the file, and the process name.

An attempt was made to access an object.
Subject:Security ID:                            CORP\jsmith
Account Name:                     jsmith
Account Domain:                  CORP
Logon ID:                               0x32B12627
Object:Object Server:                        Security
Object Type:                          File
Object Name:                        E:\Distr\Backup.rar
Handle ID:                              0x7bc4
Resource Attributes:            S:AI
Process Information:
Process ID:                             0x4
Process Name:
Access Request Information:
Accesses:                               DELETE
Access Mask:                         0x10000

file deletion audit event 4663 with username in security log

After enabling the file access auditing policy, you can find in the Security log :

  • Who deleted the file from the shared network folder and when it happened;
  • What application (process) was used to delete the file;
  • What is the date of the backup to be restored?

How to Write File Deletion Events to SQL Database (MySQL/MSSQL)?

However, even if the audit of the deleted files is enabled, it can be troublesome to find something in the logs. Firstly, it is quite hard to find a specific entry among thousands of events (in Windows there are no convenient tool to search an event with a flexible filter). Secondly, if a file was deleted a long time ago, this event may be absent in the logs, since it was overwritten by new events.

You can save all file delete events to the SQL database. You can use Microsoft SQL Server, Elasticsearch, or MySQL/MariaDB databases to store your events.

In this example, we’ll show you how to log audit events to a separate database table on MySQL. I will use the following table format:

  • Server name;
  • Name of the deleted file;
  • Date and time;
  • Name of the user who has deleted the file.

The MySQL query to create this table looks like this:

CREATE TABLE deleted_items (id INT NOT NULL AUTO_INCREMENT, server VARCHAR(100), file_name VARCHAR(255), dt_time  DATETIME, user_name VARCHAR(100),  PRIMARY KEY (ID));

To get events with EventID 4663 from the Security log for the current day, you can use the following PowerShell script:

$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName="Security";starttime="$today";id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat "%Y-%m-%d %H:%M:%S"
$File = $event.Event.EventData.Data[6]."#text"
$User = $event.Event.EventData.Data[1]."#text"
$Computer = $event.Event.System.computer
}
}

Windows Security audit - event 4663 properties

The next PowerShell script will write the data you get to the MySQL database on a remote server (with the IP address 10.1.1.13):

Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll'
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString='server=10.1.1.13;uid=posh;pwd=P@ssw0rd;database=aduser'}
$Connection.Open()
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = $Connection
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName="Security";starttime="$today";id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat "%Y-%m-%d %H:%M:%S"
$File = $event.Event.EventData.Data[6]."#text"
$File = $File.Replace(‘\’,’|’)
$User = $event.Event.EventData.Data[1]."#text"
$Computer = $event.Event.System.computer
$sql.CommandText = "INSERT INTO deleted_items (server,file_name,dt_time,user_name ) VALUES ('$Computer','$File','$Time','$User')"
$sql.ExecuteNonQuery()
}
}
$Reader.Close()
$Connection.Close()

After saving events to an external database, this Event log can be cleared.

Now, to find out who has deleted the file “AnnualReport.DOC“, it is enough to run the following script in the PowerShell console:
$DeletedFile = "%AnnualReport.DOC%"
Set-ExecutionPolicy RemoteSigned
Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll'
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString='server=10.1.1.13;uid=posh;pwd=P@ssw0rd;database=aduser'}
$Connection.Open()
$MYSQLCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter
$MYSQLDataSet = New-Object System.Data.DataSet
$MYSQLCommand.Connection=$Connection
$MYSQLCommand.CommandText="SELECT user_name,dt_time    from  deleted_items where file_name LIKE '$DeletedFile'"
$MYSQLDataAdapter.SelectCommand=$MYSQLCommand
$NumberOfDataSets=$MYSQLDataAdapter.Fill($MYSQLDataSet, "data")
foreach($DataSet in $MYSQLDataSet.tables[0])
{
write-host "User:" $DataSet.user_name "at:" $DataSet.dt_time
}
$Connection.Close()

You can now see the username and the time the file was deleted in the PS console.

select file deletion event from mysql db

Note. Since an issue has been found that the symbol “\” is not written to the database, we have replaced it for “|”. So if you have to display the full path to the file, you can perform a reverse replacement when selecting from the database:

$DataSet.file_name.Replace(‘|’,’\’).

The script of writing the information from the Event log to the database can be run at the end of the day using Task Scheduler or attached to the file deletion EventID (On Event), which is more resource-consuming. It depends on the requirements of the system.

Tip. Make sure you set the maximum size of the Security event log file to be large enough to log all events for the day. Otherwise, you will have to run the task of exporting the data to the database more often than once a day or even on the trigger. Typically, the Maximum Log Size on the workstations has to be at least 64 MB, and 262 MB on the Windows File servers. The option to overwrite old events should be left enabled (Overwrite events as needed).

If necessary, you can create a simple PHP web page to get information about the users who have deleted files in a more convenient form.

Important tip. If the log contains an entry that the file was deleted by the user, do not hurry to interpret it as a deliberate or malicious action. Many programs (especially MS Office apps) create a temporary file when saving changes and then delete the old version of the file. In this case, enable logging of process name (ProcessName fileld), from which the file was deleted, and you can parse file deletion events based on it. Or you can filter the events from such processes, like winword.exe, excel.exe, etc.

Logging File Delete Audit Events to a Text File

If you don’t want to use a separate database server, you can save file deletion audit events to a plain text log file. Use this PowerShell script to save the output to a text file:

$Outfile = "C:\Logs\Deleted-file-history-log.txt"
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @{LogName="Security";starttime="$today";id=4663} | Foreach {
$event = [xml]$_.ToXml()
if($event)
{
$Time = Get-Date $_.TimeCreated -UFormat "%Y-%m-%d %H:%M:%S"
$File = $event.Event.EventData.Data[6]."#text"
$User = $event.Event.EventData.Data[1]."#text"
$strLog = $Computer + " " + $File + " " + $Time + " " +  $User
$strLog  | out-file $Outfile –append
}
}

save file deletion events history to a text file using powershell

So, we have suggested an idea and a general model of the system to audit and store the information about the deleted files in the shared network folders. If needed, it can easily be modified to meet your requirements.

Теоретически — аудит, как уже сказано ранее. Практически — это надо сидеть и постоянно чистить логи аудита, иначе никаких дисков не хватит.

Из практики — в 90% случаев файл или каталог не удалён. Просто какое-то нерадивое чмо неловким движением мыша переместило его в какой-то каталог. Обычно — даже не заметив этого (оно само, случайно, зацепилось). Опять же из практики — подобное пропадание на Window Server — минимум 2-3 раза в месяц, а на столь же интенсивно использовавшемся Novell Netware, где подобное перемещение было запрещено соотв. атрибутом файловой системы — 2 или 3 раза за более чем 10 лет.

Настоятельно рекомендую посмотреть в сторону программного обеспечения, которое носит общее название «Сетевая корзина». Суть проста — удалённый по сети файл помещается в корзину так же, как если он удалён в локальном сеансе от имени локальной учётной записи. И восстановить просто, и видно, кто и когда удалил. А если файла в корзине нет — это те самые 90%, см. выше.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Пакет офлайн обновлений для windows 10
  • Операционная система windows это информатика
  • Windows 10 gadgets rainmeter
  • Настройка сканера на компьютере windows
  • My talking angela windows