- Разработка MiniFilter драйвера
- File System Mini Filter Driver Framework For Windows
- Transparent Cloud Storage Migration SDK
- File Monitor/File Audit — Track file change on the fly
- File Protector — Prevent unauthorized users or processes to access your sensitive data
- File Encryption Filter Driver Framework — Transparent on-access, per-file encryption
- Secure File Sharing — Control share file access with digital rights embedded
- Registry access monitoring and protection
- Process access monitoring and protection
- Secure Sandbox Solution
- ABOUT US
Разработка MiniFilter драйвера
Довелось мне как-то на работе столкнуться с задачей управления доступа и перенаправления запросов к файловой системе в рамках определенных процессов. Реализовать необходимо было простое, легко конфигурируемое решение.
Решил разрабатывать MiniFilter драйвер, конфигурируемый при помощи текстового файла.
Рассмотрим, что из себя в общем виде представляет MiniFilter:
Фильтрация осуществляется через так называемый Filter Manager, который поставляется с операционной системой Windows, активируется только при загрузке мини фильтров. Filter Manager подключается напрямую к стеку файловой системы. Мини фильтры регистрируются на обработку данных по операциям ввода/вывода при помощи функционала Filter Manager, получая, таким образом, косвенный доступ к файловой системе. После регистрации и запуска мини фильтр получает набор данных по операциям ввода/вывода, которые были указаны при конфигурировании, при необходимости может вносить изменения в эти данные, таким образом влияя на работу файловой системы.
На следующей схеме в упрощенном виде показано как функционирует Filter Manager.
Более подробную теоретическую информацию Вы можете получить на сайте MSDN, воспользовавшись ссылкой в конце статьи. Достаточно не плохо все разобрано.
Мы же двинемся в сторону разработки и рассмотрим некоторые базовые структуры, которые необходимо заполнить.
Общие глобальные данные.
В этой структуре будем хранить ссылку на объект нашего драйвера и ссылку на экземпляр фильтра. Хочу заметить, что PFLT_FILTER уникально идентифицирует мини фильтр и остается константой на все время работы драйвера. Используется при активации или остановке процесса фильтрации.
Тут стоит остановиться на нескольких поляx:
- Callbacks – ссылка на структуру, определяющую, что и при помощи каких функций мы собираемся обрабатывать.
- FilterUnload – функция, которая будет вызвана при отключении фильтра.
- FilterLoad – функция, которая будет вызвана при инициализации фильтра.
Далее рассмотрим структуру Callbacks:
Здесь мы указываем, что будем перехватывать операцию CreateFile, также указываем функции, которые будут вызываться, соответственно, до и после выполнения операции над файлом.
Далее привожу код функций, которые вызываются при инициализации и отключении фильтра.
Думаю, код не нуждается в дополнительных комментариях, так как все достаточно стандартно. Замечу только, что наш драйвер не будет работать для сети.
Теперь давайте рассмотрим функцию инициализации драйвера:
Регистрация мини фильтра осуществляется посредством вызова функции FltRegisterFilter, в которую мы передаем полученный на входе theDriverObject, структуру FilterRegistration, описанную ранее и ссылку на переменную, куда будет помещен созданный экземпляр фильтра fileManager.pFilter. Для запуска процесса фильтрации нужно вызвать функцию FltStartFiltering( fileManager.pFilter ).
Так же обращу внимание, что загрузка файла конфигурации и его обработка выполняется посредством следующих вызовов ConfigInfo = ReadConfigurationFile(); и ParseConfigurationFile(ConfigInfo) соответственно.
Данные из конфигурационного файла преобразуются в следующий набор структур.
Головной структурой выступает CONFIGURATION_MAP, которая хранит в себе ссылку на описание процесса ProcessRule, а так же указатель на следующий элемент. В свою очередь PROCESS_CONFIGURATION_RULE хранит ссылку на имя процесса и непосредственно на структуру правил перенаправления ввода/вывода, которая так же, как и REDIRECT_MAP является связным списком.
Рассмотрим функцию выгрузки драйвера, она достаточно проста:
Здесь мы лишь удаляем регистрацию фильтра и высвобождаем все наши конфигурационные структуры.
Теперь давайте обратимся к самой интересной части, а именно к функции, которая занимается перенаправлением операций ввода/вывода. Так как у нас достаточно простой драйвер, делать это мы будем прямо в PreFileOperationCallback.
Определяем основные переменные, а также проверим, не пришло ли нам уже что-то отфильтрованное, и если так, то эту операцию нужно пропустить, в противном случае мы можем получить рекурсию вызовов, что может повлечь BSOD.
Здесь обращаемся к данным структур полученных от FilterManager. Структура PFLT_CALLBACK_DATA – хранит данные по текущей операции ввода/вывода, FilterManager руководствуется полями этой структуры при обращении к файловой системе. Соответственно, если мы хотим изменить поведение Windows при обращении к файлам или каталогам, мы должны отразить это в PFLT_CALLBACK_DATA. Более конкретно, нас интересует поле Data->Iopb->TargetFileObject, используя его мы сможем получить путь до файла в текущем разделе и позже изменить его при необходимости, изменив таким образом поведение ОС. PCFLT_RELATED_OBJECTS — содержит объекты связанные с данной операцией ввода/вывода, такие как ссылку на файл, раздел и прочее. Проверим, что нужные нам элементы структуры заполнены. Также проверим, что функция в контексте которой мы выполняемся действительно MJ_CREATE.
В этом участке кода мы выделяем память для пути и имени процесса. Не представляю какого размера будет строка, так что выделяем максимально возможную строку WCHAR. Исходный код GetProcessImageName рассматривать не буду, скажу только, что она возвращает полный путь до файла в следующем виде: \Device\HarddiskVolume4\Windows\notepad.exe. т.е раздел, ну и собственно, путь до файла.
Функция FindRuleByProcessName в случае успеха возвращает первый элемент связанного списка содержащего правила перенаправления по текущему процессу, в противном случае NULL.
Высвобождаем ненужную память и проверяем то, что мы получили какой-то объект, а не NULL. redirectRuleItem = rule->ProcessRule.Rule — обращение к первому правилу для данного процесса.
Начинаем проход по всем правилам для данного процесса, сравниваем ссылку на текущий файл с тем, что у нас есть в конфигурации. Если совпало, пытаемся получить дополнительную информацию о файле, например, к какому разделу он принадлежит. Для этого используем функцию FltGetFileNameInformation.
Если все ок, пытаемся выделить раздел, после чего формируем итоговую строку. Итоговый путь = Текущий раздел + Куда направить запрос ввода/вывода.
Далее, конфигурируем системные структуры, так чтобы File Manager еще раз обработал этот запрос, но только теперь уже по другому пути. Для этого важно проставить следующие значения полей Data->IoStatus.Information = IO_REPARSE и Data->IoStatus.Status = STATUS_REPARSE;, а так же указать новый путь до файла FileObject->FileName.Buffer = fullPath.Buffer;. В качестве результата функции возвращаем FLT_PROP_COMPLETE.
Не забываем перейти к следующему элементу списка перенаправлений. FLT_PREOP_SUCCESS_NO_CALLBACK возвращаем если делать с текущей операцией Filter Manger ничего не должен.
На данный момент переопределение ввода/вывода работает только в рамках одного раздела, как только отлажу вариант с поддержкой нескольких разделов, выложу.
Устанавливать мини фильтр необходимо при помощи специально оформленного inf файла, пример, которого Вы найдете в исходниках к данной статье.
Конфигурационный файл имеет следующий вид:
Файл должен располагаться в корне диска C, имя должно быть: minifilter.conf.
Итак мы имеем возможность перенаправления запросов файлового ввода/вывода, однако реализовать в дополнение, скажем, механизм запрета доступа к файлу достаточно просто. Необходимо выделить файл, доступ к которому нужно запретить и указать следующее значение для поля системной структуры Data->IoStatus.Status = STATUS_ACCESS_DENIED;. Не забыть вернуть FLT_PROP_COMPLETE в качестве результата функции.
Чтобы стартовать или остановить сервис я использую KMD Manager. Для анализа утечек памяти PoolTag. Что касается отладки, то можно использовать DbgView, однако для Windows Vista и выше отладочные сообщения необходимо активировать, для этого нужно создать DWORD ключ в реестре по следующему пути HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Debug Print Filter с именем DEFAULT и значением 8.
Для запуска драйвера в 64 битной версии Windows 7 нужно будет отключить проверку подписи драйверов, для этого нужно перезагрузить компьютер, при старте системы нажать F8 и выбрать пункт Disable Driver Signature Enforcement, либо воспользоваться утилитой Driver Signature Enforcement Overrider(DSEO). Данная утилита позволит активировать тестовый режим отладки драйверов и подписать нужный драйвер фейковым сертификатом, что в конечном итоге позволит без проблем его использовать.
В не зависимости от того, включено логирование или нет, после запуска сервиса в DbgView Вы должны наблюдать нечто подобное.
А так наш драйвер будет выглядеть в DeviceTree
Могу добавить, что код пока еще достаточно сырой и требует доработок, однако в целом функционирует нормально. Собственно, если у Вас будет BSOD, я не виноват). Тестировал только на Windows 7 X86 и Windows 7 IA64.
File System Mini Filter Driver Framework For Windows
A file system filter driver intercepts requests targeted at a file system or another file system filter driver. By intercepting the request before it reaches its intended target, the filter driver can extend or replace functionality provided by the original target of the request.To develop file systems and file system filter drivers, use the Windows Driver Kit (WDK),which is provided by Microsoft. Even with the resources available in the Windows Driver Kit (WDK) developing file systems filter driver is certainly a challenge. To simplify your development and to provide you with a robust and well-tested file system filter driver that works with all versions and patch releases of the Windows operating systems supported by Microsoft, EaseFilter Inc. offers the file system filter driver SDK which provides a complete, modular environment for building active file system filter driver in your application.
Transparent Cloud Storage Migration SDK
File System Tiered Storage Filter Driver SDK, is a data storage technique which automatically moves data between high-cost and low-cost storage media. Tiered Storage Filter systems exist because high-speed storage devices, such as hard disk drive arrays, are more expensive (per byte stored) than slower devices, such as optical discs and magnetic tape drives. Tiered Storage Filter systems store the bulk of the enterprise’s data on slower devices. A stub is created for and replaces each migrated file in the fast disk drives. On the local system, a stub file looks and act like a regular file. When you or a Windows application accesses a migrated file stub, the Windows operating system transparently directs a file access request to the Tiered Storage Filter driver. This driver retrieves the full file from the repository to which it was migrated.
File Monitor/File Audit — Track file change on the fly
File system monitor filter can monitor the file system activities on the fly. With file system monitor filter you can monitor the file activities on file system level, capture file open,create, overwrite, read, write,query file information, set file information, query security information, set security information, file rename, file delete, directory browsing and file close I/O requests. You can develop the software for the following purposes:
- Create your own Continuous data protection (CDP) software to log the file update information, write information with offset and length in real time.
- Audit your file content.You can intercept any file system call, analyze it content, log it.
- Create Access Log, you will know who, when, what files were accessed.
- Journal the file update information. This control may be based on any file parameters, such as its location, type, size, etc. .
File Protector — Prevent unauthorized users or processes to access your sensitive data
File system control filter can control the file activities, which you can intercept the file system call, modify its content before or after the request goes down to the file system, allow/deny/cancel its execution based on the filter rule. You can fully control file open/create/overwrite, read/write, query/set file attribute/size/time security information, rename/delete, directory browsing these Io requests. With file system control filter you can developer these kinds of software:
- Create your Data protection Software. Block accessing your data based on your security policy, prevent data modification without permission.
- Create your own encryption software via encrypt the write data and decrypt the read data.
- Create your own custom security policies to control the file access.
- Hide or replace the files in the directory. You can modify the directory buffer to hide some files or change file name.
File Encryption Filter Driver Framework — Transparent on-access, per-file encryption
EaseFilter File system encryption filter driver SDK provides a comprehensive solution for transparent file level encryption. It allows developers to create transparent encryption products which it can encrypt or decrypt files on-the-fly, it can allow only authorized users or processes can access the encrypted files.
Supported strong cryptographic algorithm Rijndael is a high security algorithm which was chosen by the National Institute of Standards and Technology (NIST) as the new Advanced Encryption Standard (AES), it can support key length 128-bits,192-bits and 256-bits.
Secure File Sharing — Control share file access with digital rights embedded
Encrypt the file with 256-bits key,and embed with the digital rights management protection, only the authorized users, processes and computers can access the encrypted file.Share your files with fully control, you can expire or revoke the file access at any time, even after the file has been shared. Add or remove the authorized users, processes and computers at any time.
Registry access monitoring and protection
Monitoring registry calls to track the registry changes. When the registry key, value or security was modified, the callback routine will be invoked with a data structure that contains information that is specific to the type of registry operation.
Blocking registry calls to prevent your registry from being changed by unauthorized processes. When the registry key, value or security is going to be modified, the callback routine will be invoked with a data structure that contains information that is specific to the type of registry operation, If a RegistryCallback routine returns a status value «STATUS_ACCESS_DENIED» for a pre-notification, this registry operation will be blocked and the error code will be returned.
Modifying registry calls to create virtual registry key or value.
Process access monitoring and protection
Monitoring the process and thread creation or termination, get the notification of the process and thread operations when you register the events. Prevent the untrusted executable binaries ( malwares) from being launched, protect your data being damaged by the untrusted processes.
Process monitor and protector screenshot
Secure Sandbox Solution
A sandbox is is a secure, isolated and a tightly controlled environment where programs can be run and data can be protected. Sandboxes restrict what a piece of code can do, giving it just as many, permissions as it needs without adding additional permissions that could be abused. Prevent malicious or malfunctioning programs from running.Run untrusted Windows programs safely in Easefilter Secure Sandbox. Protect your confidential files in Easefilter Secure Sandbox
Easefilter Secure Sandbox screenshot
ABOUT US
We specialize in file system filter driver development. We architect, implement and test file system filter drivers for a wide range of functionalities. We can offer several levels of assistance to meet your specific needs.