CBEncrypt Class

Properties   Methods   Events   Config Settings   Errors  

The CBEncrypt class allows applications to transparently enforce file-level encryption and decryption policies on specified directories.

Syntax

class cbfsencrypt.CBEncrypt

Remarks

CBEncrypt monitors specified directories to ensure that all files stored there remain encrypted on disk, while allowing authorized processes to read or write decrypted content on-the-fly.

Applications define encryption rules to protect specific directories and their contents, and specify trusted processes that can access decrypted content. Any new files created or written by trusted processes within these directories are automatically encrypted according to the rules, ensuring that sensitive data is always protected at rest.

To learn more about the class's capabilities, please refer to the product's General Information topics.

Getting Started

  1. If the class's system driver has not been installed yet, call the install method to do so. This needs to be done only once.
    • In production, the driver can be installed (or updated) ahead of time with the application's installation script using the Installer DLL. Please refer to the Driver Installation topic for more information.
  2. Call the initialize method to initialize the CBEncrypt class. This must be done each time the application starts.
  3. Set the global_salt property to a string or byte array of 16 bytes in length.
  4. Add one or more encryption rules using the add_encryption_rule method. (Rules can also be added or removed after the filter is started.)
  5. Add one or more trusted processes using the add_trusted_process method.
  6. Call the start method to start filtering filesystem requests.
  7. When finished, call the stop method to stop filtering filesystem requests.
  8. To uninstall the class's system driver, call the uninstall method. This should not be done as part of the driver upgrade process.
    • In production, the driver can be uninstalled by the application's uninstallation script using the Installer DLL. Please refer to the Driver Installation topic for more information.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

activeThis property notes whether the class is active and processing requests.
altitudeThis property specifies the altitude the class's system driver should use .
encryption_rule_countThe number of records in the EncryptionRule arrays.
encryption_rule_include_subdirectoriesThis property indicates that the mask covers subdirectories and their files.
encryption_rule_passwordThis property contains the password to use for encryption.
encryption_rule_pathThis property contains the path of the directory to encrypt.
fire_volume_eventsThis property specifies the events that should be fired when a filesystem volume is mounted to or unmounted from the system.
global_saltThe value being mixed into the process of key derivation.
serialize_eventsWhether events should be fired on a single worker thread, or many.
tagThis property stores application-defined data specific to a particular instance of the class.
trusted_process_countThe number of records in the TrustedProcess arrays.
trusted_process_include_childrenWhether child processes are affected.
trusted_process_idThe Id of the target process.
trusted_process_nameThe filename of the target process's executable.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

add_encryption_ruleThis method adds a new rule for file encryption.
add_trusted_processAdds a rule that allows a process to access decrypted data of a file.
change_passwordThis method changes the password of a file.
configSets or retrieves a configuration setting.
decrypt_fileThis method decrypts a file.
encrypt_fileThis method encrypts a file.
file_matches_maskThis method checks whether a particular file or directory name matches the specified mask.
get_dos_path_nameThis method retrieves the DOS path name of the file or directory by its native (NT) path.
get_driver_statusThis method retrieves the status of the class's system driver.
get_driver_versionThis method retrieves the version of the class's system driver.
get_nt_path_nameThis method retrieves the NT (native) path name of the file or directory by its DOS path.
get_originator_process_idRetrieves the Id of the process (PID) that initiated the operation.
get_originator_process_nameRetrieves the name of the process that initiated the operation.
get_originator_tokenRetrieves the security token associated with the process that initiated the operation.
get_volume_guidThis method retrieves the volume GUID of the device targeted by a filesystem operation.
initializeThis method initializes the class.
installThis method installs (or upgrades) the class's system driver.
is_file_encryptedChecks whether the specified file is encrypted.
remove_encryption_ruleThis method removes an encryption rule from the list.
remove_trusted_processRemoves a rule that allows a process to access the decrypted data of an encrypted file.
reset_timeoutThis method resets the timeout duration for the current event handler.
shutdown_systemShuts down or reboots the operating system.
startThis method starts monitoring the filesystem and encrypting and decrypting files.
stopThis method stops monitoring of filesystem operations.
uninstallThis method uninstalls the class's system driver.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_after_filter_attach_to_volumeThis event fires after the filter attaches to a newly mounted filesystem volume.
on_after_filter_detach_from_volumeThis event fires after the filter detaches from a filesystem volume.
on_before_filter_attach_to_volumeThis event fires before the filter attaches to a newly mounted filesystem volume.
on_close_fileThis event fires when a file or directory is closed.
on_errorThis event fires if an unhandled error occurs during an event.
on_open_fileThe event fires when a file or directory is created or opened.
on_password_neededThis event fires if a password is needed to open an encrypted file.
on_progressThis event fires to indicate the progress of long-running encryption/decryption operations.
on_rename_or_move_fileThis event fires when a file is renamed or moved.

Config Settings


The following is a list of config settings for the class with short descriptions. Click on the links for further details.

DenyUntrustedWriteWhether write operations from untrusted processes are blocked.
EncryptAlternateDataStreamsWhether alternate data streams of files are also encrypted.
LazyEncryptWhether a file is encrypted or decrypted when it is written to or when it is closed.
LoggingEnabledWhether extended logging is enabled.
MaxWorkerThreadCountThe maximum number of worker threads to use to fire events.
MinWorkerThreadCountThe minimum number of worker threads to use to fire events.
NormalizeShortFileNamesWhether the driver should attempt to resolve short file names and convert them to regular ones.
ResolveNtDeviceToDriveLetterWhether native device names are translated to drive letters.
WorkerInitialStackSizeThe initial stack size to create worker threads with.
BuildInfoInformation about the product's build.
LicenseInfoInformation about the current license.

active property

This property notes whether the class is active and processing requests.

Syntax

def get_active() -> bool: ...

active = property(get_active, None)

Default Value

FALSE

Remarks

This property reflects whether the class is active and currently processing requests. It will be True after the filter has been attached successfully via a call to start.

This property is read-only.

altitude property

This property specifies the altitude the class's system driver should use .

Syntax

def get_altitude() -> str: ...
def set_altitude(value: str) -> None: ...

altitude = property(get_altitude, set_altitude)

Default Value

""

Remarks

This property specifies the altitude that the class's system driver should use . A driver's altitude determines its absolute position in the stack of filter drivers; drivers with higher altitudes are attached toward the top of the stack, closer to the user mode, which allows them to process requests earlier.

If multiple instances of the class are used, each instance must have own altitude.

Microsoft manages and assigns filesystem minifilter driver altitudes directly, so an application-specific altitude value must be obtained from Microsoft before an application is deployed in production. Please refer to the Driver Altitudes topic for more information. During development, an appropriate arbitrary value, such as 360000 (which is not registered with Microsoft), can be used.

If this property is queried before an altitude has been set (via this property or the install method), it will return an empty string.

NOTE: This property cannot be changed when active is True. Additionally, the initialize method must be called before attempting to get or set this property's value, which is stored in the registry.

encryption_rule_count property

The number of records in the EncryptionRule arrays.

Syntax

def get_encryption_rule_count() -> int: ...

encryption_rule_count = property(get_encryption_rule_count, None)

Default Value

0

Remarks

This property controls the size of the following arrays:

The array indices start at 0 and end at encryption_rule_count - 1.

This property is read-only.

encryption_rule_include_subdirectories property

This property indicates that the mask covers subdirectories and their files.

Syntax

def get_encryption_rule_include_subdirectories(encryption_rule_index: int) -> bool: ...

Default Value

TRUE

Remarks

This property indicates that the mask covers subdirectories and their files.

This property indicates that the rule covers files in the directory as specified by the mask. It also covers files in all subdirectories of this directory.

The encryption_rule_index parameter specifies the index of the item in the array. The size of the array is controlled by the encryption_rule_count property.

This property is read-only.

encryption_rule_password property

This property contains the password to use for encryption.

Syntax

def get_encryption_rule_password(encryption_rule_index: int) -> str: ...

Default Value

""

Remarks

This property contains the password to use for encryption.

This property contains the encryption password to use.

The encryption_rule_index parameter specifies the index of the item in the array. The size of the array is controlled by the encryption_rule_count property.

This property is read-only.

encryption_rule_path property

This property contains the path of the directory to encrypt.

Syntax

def get_encryption_rule_path(encryption_rule_index: int) -> str: ...

Default Value

""

Remarks

This property contains the path of the directory to encrypt.

This property contains the path of the directory, the files of which must be encrypted and decrypted. The name is converted to NT native format when the rule is added to the list by add_encrypt_rule and is used and returned in the NT native format.

The encryption_rule_index parameter specifies the index of the item in the array. The size of the array is controlled by the encryption_rule_count property.

This property is read-only.

fire_volume_events property

This property specifies the events that should be fired when a filesystem volume is mounted to or unmounted from the system.

Syntax

def get_fire_volume_events() -> int: ...
def set_fire_volume_events(value: int) -> None: ...

fire_volume_events = property(get_fire_volume_events, set_fire_volume_events)

Default Value

0

Remarks

This property specifies the events that the class should fire when a filesystem volume is mounted to or unmounted from the system. Possible values are as follows:

FS_MOUNT_IGNORE0Don't fire any events when volumes are mounted or unmounted.
FS_MOUNT_CONTROL128Fire Control Events when volumes are mounted or unmounted.

The on_before_filter_attach_to_volume, on_after_filter_attach_to_volume, and on_after_filter_detach_from_volume events will fire, synchronously, as necessary.

Note The aforementioned events are fired only for volumes mounted or unmounted after the start method is called. Typically, applications use these events to dynamically add encryption rules for removable volumes, such as USB drives.

NOTE: The methods and properties related to managing encryption rules are not intended to be used from multiple threads at once. Applications that wish to use said methods and properties from multiple threads (e.g., during the on_after_filter_attach_to_volume and on_after_filter_detach_from_volume events) are responsible for employing proper thread synchronization techniques to ensure that manipulation and enumeration of the lists occur in a thread-safe manner.

global_salt property

The value being mixed into the process of key derivation.

Syntax

def get_global_salt() -> bytes: ...
def set_global_salt(value: bytes) -> None: ...

global_salt = property(get_global_salt, set_global_salt)

Default Value

""

Remarks

This property specifies a global salt value that is mixed into the key derivation process when deriving an encryption key from a password. A salt increases security by ensuring that identical passwords produce different keys.

This property should be set to a random string or byte array of 16 bytes in length. If the value is longer than 16 bytes, only the first 16 bytes are used. If the value is shorter than 16 bytes, the start method will throw an exception.

Using a cryptographically strong random number generator is recommended for increased security.

serialize_events property

Whether events should be fired on a single worker thread, or many.

Syntax

def get_serialize_events() -> int: ...
def set_serialize_events(value: int) -> None: ...

serialize_events = property(get_serialize_events, set_serialize_events)

Possible Values

0   # OnMultipleThreads
1 # OnOneWorkerThread

Default Value

0

Remarks

This property specifies whether the class should fire all events serially on a single worker thread, or concurrently on multiple worker threads. The possible values are:

0 (seOnMultipleThreads) The class fires events in the context of multiple worker threads. The MinWorkerThreadCount and MaxWorkerThreadCount configuration settings control how many worker threads are used for this.
1 (seOnOneWorkerThread) The class fires events in the context of one background worker thread.

Please refer to the Threading and Concurrency topic for more information.

NOTE: This property cannot be changed when active is True, and it cannot be changed within events.

tag property

This property stores application-defined data specific to a particular instance of the class.

Syntax

def get_tag() -> int: ...
def set_tag(value: int) -> None: ...

tag = property(get_tag, set_tag)

Default Value

0

Remarks

This property can be used to store data specific to a particular instance of the class.

trusted_process_count property

The number of records in the TrustedProcess arrays.

Syntax

def get_trusted_process_count() -> int: ...

trusted_process_count = property(get_trusted_process_count, None)

Default Value

0

Remarks

This property controls the size of the following arrays:

The array indices start at 0 and end at trusted_process_count - 1.

This property is read-only.

trusted_process_include_children property

Whether child processes are affected.

Syntax

def get_trusted_process_include_children(trusted_process_index: int) -> bool: ...

Default Value

FALSE

Remarks

Whether child processes are affected.

This property indicates whether the rule applies to children of the target process.

The trusted_process_index parameter specifies the index of the item in the array. The size of the array is controlled by the trusted_process_count property.

This property is read-only.

trusted_process_id property

The Id of the target process.

Syntax

def get_trusted_process_id(trusted_process_index: int) -> int: ...

Default Value

0

Remarks

The Id of the target process.

This property reflects the target process's Id (PID). Will be 0 if the target process was specified by trusted_process_process_name, or -1 if the rule applies to all processes.

The trusted_process_index parameter specifies the index of the item in the array. The size of the array is controlled by the trusted_process_count property.

This property is read-only.

trusted_process_name property

The filename of the target process's executable.

Syntax

def get_trusted_process_name(trusted_process_index: int) -> str: ...

Default Value

""

Remarks

The filename of the target process's executable.

This property reflects the full file name of the target process's executable. Will be empty if the target process was specified by trusted_process_process_id (or if the rule applies to all processes, in which case trusted_process_process_id will be -1).

The trusted_process_index parameter specifies the index of the item in the array. The size of the array is controlled by the trusted_process_count property.

This property is read-only.

add_encryption_rule method

This method adds a new rule for file encryption.

Syntax

def add_encryption_rule(path: str, include_subdirectories: bool, password: str) -> bool: ...

Remarks

This method adds a new encryption rule that defines how certain files must be encrypted and decrypted.

The Path parameter must be a valid path to the directory, in which files will be encrypted, and IncludeSubdirectories specifies whether or not the rule is recursive (i.e., covers files in subdirectories).

To encrypt a file, the Password parameter is used.

For more information, see Encryption.

The class stores the parameters in the list. Adding the same path several times will create only one rule for each distinct path, and consequent calls to add_encryption_rule with different parameters will be ignored. The application can remove a rule using the remove_encryption_rule method, and then can add a new rule using add_encryption_rule.

The method will return True if the rule was added to the list and False otherwise.

NOTE: The methods and properties related to managing encryption rules are not intended to be used from multiple threads at once. Applications that wish to use said methods and properties from multiple threads (e.g., during the on_after_filter_attach_to_volume and on_after_filter_detach_from_volume events) are responsible for employing proper thread synchronization techniques to ensure that manipulation and enumeration of the lists occur in a thread-safe manner.

add_trusted_process method

Adds a rule that allows a process to access decrypted data of a file.

Syntax

def add_trusted_process(process_file_name: str, process_id: int, child_processes: bool) -> None: ...

Remarks

This method can be used to add an access rule that grants the process specified by ProcessFileName or ProcessId access to decrypted data of an encrypted file. If no rules are added, access is not permitted to any process.

Processes that are already running can be specified by passing their process Id (PID) for the ProcessId parameter (in which case ProcessFileName should be empty). Processes that have not yet started can be specified by passing the full file name of the process's executable file for ProcessFileName (in which case ProcessId should be set to 0). If ProcessName is empty, and ProcessId is -1, the new rule will apply to all processes. When adding a PID-based rule, you need to be aware of the PID Reuse behavior of Windows.

ChildProcesses controls whether the rule also applies to children of the target process.

To remove the process access rule later, pass the same ProcessFileName and ProcessId values to the remove_trusted_process method.

NOTE: This method cannot be called within events.

The methods and properties related to process access lists are not intended to be used from multiple threads at once. Applications that wish to use said methods and properties from multiple threads are responsible for employing proper thread synchronization techniques to ensure that manipulation and enumeration of process access information occurs in a thread-safe manner.

change_password method

This method changes the password of a file.

Syntax

def change_password(file_name: str, old_password: str, new_password: str) -> None: ...

Remarks

This method changes the password used to encrypt the file specified by FileName.

If the file is not encrypted and the new password is not empty, the file will be encrypted. If the file is encrypted and the new password is empty, the file will be decrypted.

The OldPassword parameter specifies the current encryption password, if applicable.

The NewPassword parameter specifies the new encryption password to use, if applicable.

config method

Sets or retrieves a configuration setting.

Syntax

def config(configuration_string: str) -> str: ...

Remarks

config is a generic method available in every class. It is used to set and retrieve configuration settings for the class.

These settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the config method.

To set a configuration setting named PROPERTY, you must call Config("PROPERTY=VALUE"), where VALUE is the value of the setting expressed as a string. For boolean values, use the strings "True", "False", "0", "1", "Yes", or "No" (case does not matter).

To read (query) the value of a configuration setting, you must call Config("PROPERTY"). The value will be returned as a string.

decrypt_file method

This method decrypts a file.

Syntax

def decrypt_file(file_name: str, password: str) -> None: ...

Remarks

This method decrypts the file specified by FileName.

If the file is not encrypted, the method returns.

The Password parameter specifies the password to use to decrypt the file.

encrypt_file method

This method encrypts a file.

Syntax

def encrypt_file(file_name: str, password: str) -> None: ...

Remarks

This method encrypts the file specified by FileName, if it is not already encrypted.

If the file is encrypted, the method reports an error. Use change_password method to change the file password.

The Password parameter specifies the encryption password to use.

file_matches_mask method

This method checks whether a particular file or directory name matches the specified mask.

Syntax

def file_matches_mask(mask: str, file_name: str, case_sensitive: bool) -> bool: ...

Remarks

This method checks whether the file or directory name specified by FileName matches Mask; if it does, this method returns True. The CaseSensitive parameter controls whether a case-sensitive match should be performed.

NOTE: This method does not handle so-called DOS_* wildcards (DOS_STAR, DOS_QM, DOS_DOT). The explanation about the characters can be found in the MSDN article. If you have a mask that includes one of those characters on Windows, you can use the RtlIsNameInExpression function of Windows API.

NOTE: As the explanation states, "When you do a case-insensitive search and do not provide a translation table, the name is converted to uppercase."

get_dos_path_name method

This method retrieves the DOS path name of the file or directory by its native (NT) path.

Syntax

def get_dos_path_name(nt_path: str) -> str: ...

Remarks

This method retrieves the DOS path name of the file or directory by its native path, specified in the NTPath parameter.

NOTE: Such name conversion is not always possible (e.g., the volume can have none or more than one DOS names). In this case, an empty string is returned.

NOTE: This method can be called only within events, and it must be called in the same thread that the event was originally fired on.

get_driver_status method

This method retrieves the status of the class's system driver.

Syntax

def get_driver_status(product_guid: str) -> int: ...

Remarks

This method retrieves the status of the class's system driver. This status can then be used to verify whether it has been properly installed and is ready for use.

The value returned by the method corresponds to the dwCurrentState field of the SERVICE_STATUS structure from the Windows API. It will be one of the following:

MODULE_STATUS_NOT_PRESENT0x00000000The specified module is not present on the system.

MODULE_STATUS_STOPPED0x00000001The specified module is in the Stopped state.

MODULE_STATUS_RUNNING0x00000004The specified module is loaded and running.

ProductGUID is used to distinguish among driver installations performed by different applications as well as separate filter instances. Such information is necessary to guard against unexpected situations, such as the driver being uninstalled by one application despite other applications still needing it.

Therefore, to ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

Additionally, some per-instance settings are stored in the GUID-specific registry keys. If multiple instances of the class are used, each instance must have own ProductGUID, and the driver must be installed several times.

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

NOTE: This method cannot be called within events.

get_driver_version method

This method retrieves the version of the class's system driver.

Syntax

def get_driver_version(product_guid: str) -> int: ...

Remarks

This method retrieves the version of the class's system driver. The value is returned as a 64-bit integer composed of four 16-bit words that each correspond to a piece of the overall module version. For example, a version of 2.32.6.28 would cause the value 0x000200200006001C to be returned.

If the class's system driver is not installed, this method returns 0.

ProductGUID is used to distinguish among driver installations performed by different applications as well as separate filter instances. Such information is necessary to guard against unexpected situations, such as the driver being uninstalled by one application despite other applications still needing it.

Therefore, to ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

Additionally, some per-instance settings are stored in the GUID-specific registry keys. If multiple instances of the class are used, each instance must have own ProductGUID, and the driver must be installed several times.

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

NOTE: This method cannot be called within events.

get_nt_path_name method

This method retrieves the NT (native) path name of the file or directory by its DOS path.

Syntax

def get_nt_path_name(dos_path: str) -> str: ...

Remarks

This method retrieves the NT (native) path name of the file or directory by its path, specified in the DOSPath parameter.

get_originator_process_id method

Retrieves the Id of the process (PID) that initiated the operation.

Syntax

def get_originator_process_id() -> int: ...

Remarks

This method can be called within events fired for filesystem operations to retrieve the Id of the process (PID) that initiated the operation. If the query fails, this method returns 0.

Please note that PIDs are not unique, and may be reused by different processes over time.

Applications cannot use this method to retrieve information about remote processes accessing virtual drives shared on the network. Windows does not provide such information due to the nature of remote access.

NOTE: This method can be called only within events, and it must be called in the same thread that the event was originally fired on.

get_originator_process_name method

Retrieves the name of the process that initiated the operation.

Syntax

def get_originator_process_name() -> str: ...

Remarks

This method can be called within events fired for filesystem operations to retrieve the name of the process that initiated the operation. If the query fails, this method returns empty string.

Applications cannot use this method to retrieve information about remote processes accessing virtual drives shared on the network. Windows does not provide such information due to the nature of remote access.

NOTE: This method can be called only within events, and it must be called in the same thread that the event was originally fired on.

get_originator_token method

Retrieves the security token associated with the process that initiated the operation.

Syntax

def get_originator_token() -> int: ...

Remarks

This method can be called within events fired for filesystem operations to retrieve the security token associated with the process that initiated the operation. If the query fails, this method returns INVALID_HANDLE_VALUE. NOTE: To use this method from Notify* event handlers, you need to enable the CaptureTokenForNotifyEvents setting.

The security token returned by this method can be passed to the Windows API's GetTokenInformation function to obtain more information about the process. This is particularly useful for implementing custom security checks; please refer to the Security Checks topic for more information.

Important: When applications are finished using the returned security token, they must close it using the Windows API's CloseHandle function.

Network Access Notes

For virtual drives shared on the network, applications may wish to obtain information about the network users accessing it (e.g., account names). Drives can be shared in several modes in Windows, which can affect the information retrievable via the security token this method returns:

  • Authenticated mode, in which case the Helper DLL (which, in general, is responsible for relaying remote drive requests to and from the system driver) will impersonate the network user, allowing that account's actual information to be retrieved.
  • Guest mode, in which case the retrievable information is for the system's GUEST account.
  • Administrative shares (those which exist by default and whose names end with '$'; e.g., C$, ADMIN$, etc.), in which case the retrievable information is for the LOCAL_SYSTEM account.

NOTE: This method can be called only within events, and it must be called in the same thread that the event was originally fired on.

get_volume_guid method

This method retrieves the volume GUID of the device targeted by a filesystem operation.

Syntax

def get_volume_guid() -> str: ...

Remarks

This method can be called within events fired for filesystem operations to retrieve the volume GUID of the device targeted by the operation, returned in the Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} format. If the query fails, this method returns an empty string.

Volume GUIDs can be used to enumerate the mounting points of a device using the Windows API's GetVolumePathNamesForVolumeName function.

NOTE: This method can be called only within events.

initialize method

This method initializes the class.

Syntax

def initialize(product_guid: str) -> None: ...

Remarks

This method initializes the class and must be called each time the application starts before attempting to call any of the class's other methods with the exception of installation-related methods.

ProductGUID is used to distinguish between driver installations performed by different applications. Such information is necessary to guard against unexpected situations such as, e.g., the driver being uninstalled by one application despite other applications still needing it.

The GUID must be specified in so-called "Registry Format" (e.g., "{1FAD0EF2-9A03-4B87-B4BC-645B7035ED90}") with curly braces included.

To ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

If the required driver was not installed using the install method with the same value of ProductGUID, initialize will return a ERROR_FILE_NOT_FOUND error (Win32 error code 2).

If the loaded kernel-mode driver is older than the user-mode API, initialize will return a ERROR_INVALID_KERNEL_INFO_VERSION error (Win32 error code 340). In this situation, an update of the driver using the install method is required before the class can be used.

install method

This method installs (or upgrades) the class's system driver.

Syntax

def install(cab_file_name: str, product_guid: str, path_to_install: str, altitude: str, flags: int, allowed_controllers: str) -> bool: ...

Remarks

This method is used to install or upgrade the class's system driver. If the system must be rebooted to complete the installation process, this method returns True; otherwise, it returns False.

Important: To upgrade the product's modules, use only the install method. Previously installed versions of the modules should not be uninstalled first. Calling the install method will upgrade the previously installed version.

Please refer to the Driver Installation topic for more information.

CabFileName must be the path of the cbfilter.cab file containing the class's system driver.

NOTE: This .cab file must remain on the target system (or be available in some other way) after installation, as it is required to uninstall the driver from the system.

ProductGUID is used to distinguish among driver installations performed by different applications as well as separate filter instances. Such information is necessary to guard against unexpected situations, such as the driver being uninstalled by one application despite other applications still needing it.

Therefore, to ensure proper operation, it is critical that each individual application have its own unique ProductGUID value, and that applications (and their installation scripts) use that value when calling any of the following methods:

Additionally, some per-instance settings are stored in the GUID-specific registry keys. If multiple instances of the class are used, each instance must have own ProductGUID, and the driver must be installed several times.

PathToInstall controls where the driver is installed. Pass empty string (highly recommended) to automatically install them to the appropriate Windows system directory.

Altitude specifies the driver altitude to use . During development, you can use any acceptable altitude value. For deployment, an altitude value must be assigned by Microsoft before deploying a filesystem minifilter in production. After installation, the altitude can be changed at any time using the altitude property. Please refer to the Driver Altitudes topic for more information.

If multiple instances of the class are used, each instance must have own altitude.

Flags specifies various installation options. It should be created by OR'ing together (e.g., "CONST_A | CONST_B") zero or more of the following flags:

INSTALL_REMOVE_OLD_VERSIONS0x00000001Uninstall drivers from previous class versions (e.g., 2020).

INSTALL_KEEP_START_TYPE0x00000002Keep the driver's current start type setting in the registry.

If this flag is not set (default), the installation logic will reset the driver's start type setting in the Windows registry to the default value. Setting this flag causes the installation logic to preserve the current value, which may be necessary if the user (or the application) set it previously.

INSTALL_OVERWRITE_SAME_VERSION0x00000004Install the driver file when its version and build number is the same as the version of the already installed driver.

INSTALL_REQUESTS_VIA_DRIVER_STACK0x00001000Whether internal requests to the filesystem are sent directly to the filesystem driver or through the stack of filesystem filter drivers.

This flag is applicable only for CBFILTER and CBMONITOR.

After installation, the effects of this flag can be changed using the SendRequestsViaDriverStack configuration setting.

INSTALL_ALWAYS_PREPARE_FILES0x00010000Whether the driver should keep track of information for files that are already open when (i.e., were opened before) the class is initialized.

This flag is applicable only for CBFILTER and CBMONITOR.

If this flag is set, the driver will prepare information about each file as it is opened, regardless of whether a CBFILTER/CBMONITOR-based application is actually running at the time. This information then allows applications to receive events for any files that are already open when the CBFILTER/CBMONITOR class is initialized.

NOTE: These preparations will slow down all file open operations; do not enable this feature unless it is actually necessary.

After installation, the effects of this flag can be changed using the AlwaysPrepareFiles configuration setting.

INSTALL_FORCE_APP_PERMISSION_CHECK0x00020000Whether the driver should require the controller process to have elevated or system privileges.

This flag is not applicable for CBPROCESS.

If this flag is set, the driver will verify that the controller process is a system service (or is executing with elevated privileges) anytime a file is opened. If the controller process does not meet these requirements, the file will be skipped (i.e., not filtered in any way).

NOTE: This additional verification will slow down all file open operations.

After installation, the effects of this flag can be changed using the ForceAppPermissionCheck configuration setting.

INSTALL_FORCE_SECURITY_CHECKS0x00040000Whether the driver should prevent the controller process from filtering files that it would not normally have access to.

This flag is not applicable for CBPROCESS.

If this flag is set, the driver will check the security permissions of the controller process anytime a file is opened to verify that the process has access to the file. If the controller process does not have access to the file, the file will be skipped (i.e., not filtered in any way). For example, if this flag is set and the controller process is running with limited privileges, then the driver will not allow it to filter files that require greater privileges to access.

NOTE: This additional verification will slow down all file open operations.

After installation, the effects of this flag can be changed using the ForceSecurityChecks configuration setting.

INSTALL_SKIP_PREPARING_FILES_WITH_NO_RULES0x00080000Whether the driver should keep track of information for opened files which are not covered by any rules.

This flag is applicable only for CBFILTER and CBMONITOR.

If this flag is not set, the driver will prepare information about each file as it is opened, regardless of whether this file matches any of the rules tha exist at the time of file opening. The prepared information is used to keep track of file names (especially during file renaming or when hard links are managed).

This flag can be used to optimize the filtering process and reduce the load on the kernel memory in scenarios, where filtering rules are defined beforehand and cover only a subset of files or directories. I.e., the flag brings no benefit if a rule is set with the "*.*" mask or when it is set to "C:\*.*" with only drive C: available in the system.

The flag will be effective only when all instances of the class have it set. If any of the instances doesn't have it set, the information is prepared for all files and is used for all instances.

After installation, the effects of this flag can be changed using the SkipPreparingFilesWithNoRules configuration setting.

NOTE: Enabling the AlwaysPrepareFiles and/or SendRequestsViaDriverStack configuration settings before calling this method will cause the corresponding flags to be added automatically. These configuration settings can also be used to toggle the corresponding options at any time after installation.

AllowedControllers is the optional parameter that makes it possible to limit communication with the driver to just the predefined set of processes. When the caller specifies one or more names of the executable files, filtering can be started with the specified ProductGUID only when filtering is initiated by the process created from one of the listed executable files. If the name of the caller process does not match any of the allowed names, the call to start will fail with an error.

The parameter may be either empty or contain one or more EXE file names with complete paths. Separate names/paths should be separated by the LF character (numeric code 10).

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

This method requires administrative rights to execute successfully. If the user account of the process that calls this method doesn't have such rights, the call will fail with an ERROR_PRIVILEGE_NOT_HELD (0x0522) error.

NOTE: This method cannot be called within events.

is_file_encrypted method

Checks whether the specified file is encrypted.

Syntax

def is_file_encrypted(file_name: str) -> bool: ...

Remarks

This method checks whether the file specified by FileName is encrypted using the class.

remove_encryption_rule method

This method removes an encryption rule from the list.

Syntax

def remove_encryption_rule(path: str) -> bool: ...

Remarks

This method removes an encryption rule, identified by Path, from the list of encrypted rules.

The method will return True if the rule that includes the path was found in the list and was removed, and False otherwise.

NOTE: The methods and properties related to managing encryption rules are not intended to be used from multiple threads at once. Applications that wish to use said methods and properties from multiple threads (e.g., during the on_after_filter_attach_to_volume and on_after_filter_detach_from_volume events) are responsible for employing proper thread synchronization techniques to ensure that manipulation and enumeration of the lists occur in a thread-safe manner.

remove_trusted_process method

Removes a rule that allows a process to access the decrypted data of an encrypted file.

Syntax

def remove_trusted_process(process_file_name: str, process_id: int) -> None: ...

Remarks

This method can be used to remove an access rule previously added with the add_trusted_process method.

Pass the same values for ProcessFileName and ProcessId as were used to add the rule when add_trusted_process was called previously. Please refer to that method's documentation for more information.

NOTE: This method cannot be called within events.

The methods and properties related to process access lists are not intended to be used from multiple threads at once. Applications that wish to use said methods and properties from multiple threads are responsible for employing proper thread synchronization techniques to ensure that manipulation and enumeration of process access information occurs in a thread-safe manner.

reset_timeout method

This method resets the timeout duration for the current event handler.

Syntax

def reset_timeout(timeout: int) -> bool: ...

Remarks

When event timeouts are being enforced, this method can be called within an event handler to inform the class that request processing is taking longer than expected.

If called successfully, this method returns True, and the current event handler's timeout timer is immediately reset to 0; when it reaches the number of milliseconds specified by Timeout, the driver will either "release" the underlying request and pass it onwards, or cancel it by reporting an error; whichever is most appropriate for the event in question. Please refer to the Timeouts topic for more information.

Passing 0 for Timeout disables the timeout timer for the current event handler, allowing it to take as long as it needs to complete.

NOTE: When several events are fired for the same file concurrently (if the SerializeAccess configuration setting is disabled), and reset_timeout is called from one of the handlers of these events, this method will reset the timer for all currently executed event handlers.

NOTE: This method can be called only within events.

shutdown_system method

Shuts down or reboots the operating system.

Syntax

def shutdown_system(shutdown_prompt: str, timeout: int, force_close_apps: bool, reboot: bool) -> bool: ...

Remarks

This method shuts down or (if Reboot is True) reboots the operating system. If the appropriate privileges cannot be obtained, or if the InitiateSystemShutdown system call returns False, then this method will return False; otherwise, it returns True. This method can be used if the installation or uninstallation function requires the system to be rebooted in order to complete.

ShutdownPrompt, if non-empty, specifies a message that the OS should display to the user for Timeout seconds. If empty string is passed for ShutdownPrompt, no message is displayed and the Timeout parameter's value is ignored.

ForceCloseApps specifies whether the OS should forcefully close all applications. Please keep in mind that forceful closing of applications with unsaved data can lead to data loss.

Reboot specifies whether the OS should reboot (True) or just shut down (False).

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

NOTE: This method cannot be called within events.

start method

This method starts monitoring the filesystem and encrypting and decrypting files.

Syntax

def start(timeout: int) -> None: ...

Remarks

This method starts filesystem monitoring and handling of operations with files that must be encrypted or decrypted. Rules can be added and removed both before and after this method is called, so long as the initialize method is called before doing anything else.

This method can fail for a number of reasons, including (but not limited to) the following:

  • If the class's system driver has not been properly installed, or is awaiting a system reboot (as indicated by the return value of install), this method fails with an ERROR_FILE_NOT_FOUND (2) error code.
  • If the initialize method has not been called yet, this method fails with an ERROR_NOT_READY (21) error code.
  • If the filter is already active, this method fails with an ERROR_CONNECTION_ACTIVE (1230) error code.
  • If an invalid value is passed for Timeout, this method fails with an ERROR_IMPLEMENTATION_LIMIT (1292) error code.

Timeout

Timeout specifies how many milliseconds the driver should wait for events to execute before releasing or cancelling the underlying OS requests; please refer to the Timeouts topic for more information. Valid values are 0, which disables event timeouts, and values greater than or equal to 3000. When event timeouts are in effect, event handlers can call reset_timeout to reset the timer if they require additional time to complete.

stop method

This method stops monitoring of filesystem operations.

Syntax

def stop() -> None: ...

Remarks

This method stops monitoring of filesystem operations and encrypting and decrypting files.

The method returns after monitoring is stopped.

uninstall method

This method uninstalls the class's system driver.

Syntax

def uninstall(cab_file_name: str, product_guid: str, installed_path: str, flags: int) -> bool: ...

Remarks

This method is used to uninstall the class's system driver. If the system must be rebooted to complete the uninstallation process, this method returns True; otherwise, it returns False.

Important: To upgrade the product's modules, use only the install method. Previously installed versions of the modules should not be uninstalled first. Calling the install method will upgrade the previously installed version.

Please refer to the Driver Installation topic for more information.

The same values must be passed for the CabFileName, ProductGUID, and InstalledPath parameters as were passed when install was called; please refer to its documentation for more information.

Flags specifies which versions of the class's system driver should be uninstalled and which should be set by OR'ing together (e.g., "CONST_A | CONST_B") one or more of the following values:

UNINSTALL_VERSION_PREVIOUS0x00000001Uninstall modules from previous product versions.

UNINSTALL_VERSION_CURRENT0x00000002Uninstall modules from the current product version.

UNINSTALL_VERSION_ALL0x00000003Uninstall modules from all product versions.

This method is available in both the class API and the Installer DLL included with the product; please refer to the Driver Installation topic for more information about the latter.

This method requires administrative rights to execute successfully. If the user account of the process that calls this method doesn't have such rights, the call will fail with an ERROR_PRIVILEGE_NOT_HELD (0x0522) error.

NOTE: This method cannot be called within events.

on_after_filter_attach_to_volume event

This event fires after the filter attaches to a newly mounted filesystem volume.

Syntax

class CBEncryptAfterFilterAttachToVolumeEventParams(object):
  @property
  def volume_name() -> str: ...

  @property
  def volume_name_nt() -> str: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_after_filter_attach_to_volume() -> Callable[[CBEncryptAfterFilterAttachToVolumeEventParams], None]: ...
@on_after_filter_attach_to_volume.setter
def on_after_filter_attach_to_volume(event_hook: Callable[[CBEncryptAfterFilterAttachToVolumeEventParams], None]) -> None: ...

Remarks

This event fires after the filter attaches to the newly mounted filesystem volume specified by VolumeNameNT and, when possible, VolumeName. Please refer to the fire_volume_events property for more information.

Applications need to handle this event only if the fire_volume_events property includes the FS_MOUNT_CONTROL flag.

NOTE: This event won't fire for any volumes skipped during the on_before_filter_attach_to_volume event; please refer to its documentation for more information.

VolumeNameNT contains the name of the volume in the NT-native format, as received from the system. If the ResolveNtDeviceToDriveLetter configuration setting is enabled, and if it was possible to convert the NT name to the DOS format with a drive letter, VolumeName will contain the name in this format; otherwise, it will be empty.

Applications can obtain additional information about a volume by retrieving its GUID using the get_volume_guid method, and then using that GUID to call various Windows API functions.

Applications can use this event to add volume-specific rules for the volume that has been mounted (keeping in mind that this event does not fire for volumes that are already present when start is called). Applications that intend to do so must ensure that proper thread synchronization techniques are used when manipulating or enumerating the rule lists, because this event's handler will always execute in the context of some worker thread. Note: if a path-based rule is added or removed, such a path should use the value from VolumeNameNT to avoid a possible deadlock, which may occur during resolving a DOS name to the NT format.

Applications must be aware that this event fires as a direct response to a filesystem state change (mount or unmount). Various system components or third-party actors can perform supplementary filesystem mounting and unmounting during main unmount operations (e.g., Volume Service is one such component). This can cause seemingly excessive events to be fired, and sometimes they can be fired out of order (such as two *Attach or *Detach events fired in a row).

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

on_after_filter_detach_from_volume event

This event fires after the filter detaches from a filesystem volume.

Syntax

class CBEncryptAfterFilterDetachFromVolumeEventParams(object):
  @property
  def volume_name() -> str: ...

  @property
  def volume_name_nt() -> str: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_after_filter_detach_from_volume() -> Callable[[CBEncryptAfterFilterDetachFromVolumeEventParams], None]: ...
@on_after_filter_detach_from_volume.setter
def on_after_filter_detach_from_volume(event_hook: Callable[[CBEncryptAfterFilterDetachFromVolumeEventParams], None]) -> None: ...

Remarks

This event fires after the filter detaches from the filesystem volume specified by VolumeNameNT and, when possible, VolumeName, typically because of the volume being unmounted. Please refer to the fire_volume_events property for more information.

Applications need to handle this event only if the fire_volume_events property includes the FS_MOUNT_CONTROL flag.

NOTE: This event won't fire for any volumes skipped during the on_before_filter_attach_to_volume event; please refer to its documentation for more information.

Applications should use this event to remove volume-specific rules for the volume that has been unmounted. Applications that intend to do so must ensure that proper thread synchronization techniques are used when manipulating or enumerating the rule lists, because this event's handler will always execute in the context of some worker thread. Note: if a path-based rule is added or removed, such a path should use the value from VolumeNameNT to avoid a possible deadlock, which may occur during resolving a DOS name to the NT format.

Applications must be aware that this event fires as a direct response to a filesystem state change (mount or unmount). Various system components or third-party actors can perform supplementary filesystem mounting and unmounting during main unmount operations (e.g., Volume Service is one such component). This can cause seemingly excessive events to be fired, and sometimes they can be fired out of order (such as two *Attach or *Detach events fired in a row).

VolumeNameNT contains the name of the volume in the NT-native format, as received from the system. If the ResolveNtDeviceToDriveLetter configuration setting is enabled, and if it was possible to convert the NT name to the DOS format with a drive letter, VolumeName will contain the name in this format; otherwise, it will be empty.

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

on_before_filter_attach_to_volume event

This event fires before the filter attaches to a newly mounted filesystem volume.

Syntax

class CBEncryptBeforeFilterAttachToVolumeEventParams(object):
  @property
  def volume_name() -> str: ...

  @property
  def volume_name_nt() -> str: ...

  @property
  def skip_volume() -> bool: ...
  @skip_volume.setter
  def skip_volume(value) -> None: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_before_filter_attach_to_volume() -> Callable[[CBEncryptBeforeFilterAttachToVolumeEventParams], None]: ...
@on_before_filter_attach_to_volume.setter
def on_before_filter_attach_to_volume(event_hook: Callable[[CBEncryptBeforeFilterAttachToVolumeEventParams], None]) -> None: ...

Remarks

This event fires before the filter attaches to the newly mounted filesystem volume specified by VolumeNameNT and, when possible, VolumeName. Please refer to the fire_volume_events property for more information.

Applications need to handle this event only if the fire_volume_events property includes the FS_MOUNT_CONTROL flag.

VolumeNameNT contains the name of the volume in the NT-native format, as received from the system. If the ResolveNtDeviceToDriveLetter configuration setting is enabled, and if it was possible to convert the NT name to the DOS format with a drive letter, VolumeName will contain the name in this format; otherwise, it will be empty.

Applications can obtain additional information about a volume by retrieving its GUID using the get_volume_guid method, and then using that GUID to call various Windows API functions.

The SkipVolume parameter specifies whether the class's system driver should skip the specified volume (i.e., not attach the filter to it). Setting this parameter to True will cause all filesystem operations that target to volume to be completely ignored by the class's system driver. It also will prevent any of the following events from firing for the volume:

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

Applications must be aware that this event fires as a direct response to a filesystem state change (mount or unmount). Various system components or third-party actors can perform supplementary filesystem mounting and unmounting during main unmount operations (e.g., Volume Service is one such component). This can cause seemingly excessive events to be fired, and sometimes they can be fired out of order (such as two *Attach or *Detach events fired in a row).

on_close_file event

This event fires when a file or directory is closed.

Syntax

class CBEncryptCloseFileEventParams(object):
  @property
  def file_name() -> str: ...

  @property
  def desired_access() -> int: ...

  @property
  def create_disposition() -> int: ...

  @property
  def encrypted() -> bool: ...

  @property
  def modified() -> bool: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_close_file() -> Callable[[CBEncryptCloseFileEventParams], None]: ...
@on_close_file.setter
def on_close_file(event_hook: Callable[[CBEncryptCloseFileEventParams], None]) -> None: ...

Remarks

This event fires when the file or directory specified by FileName is closed, but only when the file was opened for reading or writing (not for retrieving attributes).

An application can use this event to schedule an asynchronous encryption or decryption operation on the file.

The DesiredAccess and CreateDisposition parameters are the same as the ones that were passed with the on_open_file event that opened the file.

The Encrypted parameter indicates whether the file is currently encrypted.

The Modified parameter indicates whether the file was modified while being opened. Modifications include writing to the file, changing its size or Valid Data Length, as well as opening a file in one of the overwrite or "supersede" modes, in which file contents are replaced.

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

on_error event

This event fires if an unhandled error occurs during an event.

Syntax

class CBEncryptErrorEventParams(object):
  @property
  def error_code() -> int: ...

  @property
  def description() -> str: ...

# In class CBEncrypt:
@property
def on_error() -> Callable[[CBEncryptErrorEventParams], None]: ...
@on_error.setter
def on_error(event_hook: Callable[[CBEncryptErrorEventParams], None]) -> None: ...

Remarks

This event fires if an unhandled error occurs during another event. Developers can use this information to track down unhandled errors in an application's event handlers.

on_open_file event

The event fires when a file or directory is created or opened.

Syntax

class CBEncryptOpenFileEventParams(object):
  @property
  def file_name() -> str: ...

  @property
  def file_exists() -> bool: ...

  @property
  def existing_attributes() -> int: ...

  @property
  def desired_access() -> int: ...

  @property
  def attributes() -> int: ...

  @property
  def share_mode() -> int: ...

  @property
  def options() -> int: ...

  @property
  def create_disposition() -> int: ...

  @property
  def encryption() -> int: ...
  @encryption.setter
  def encryption(value) -> None: ...

  @property
  def password() -> str: ...
  @password.setter
  def password(value) -> None: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_open_file() -> Callable[[CBEncryptOpenFileEventParams], None]: ...
@on_open_file.setter
def on_open_file(event_hook: Callable[[CBEncryptOpenFileEventParams], None]) -> None: ...

Remarks

This event fires when the file or directory specified by FileName is created or opened. You can use the FileExists parameter to detect whether the file exists and the CreateDisposition parameter to determine what will happen with the data after the file is opened.

The initial values of DesiredAccess, Attributes, ShareMode, and CreateDisposition parameters reflect the values that were passed for the similarly named parameters of the Windows API's CreateFile function (or, more accurately, the values carried by the IRP_MJ_CREATE I/O Request Packet).

DesiredAccess may contain one or more of the following access flags:

DESIRED_ACCESS_FILE_LIST_DIRECTORY0x00000001For a directory, the right to list the contents of the directory.

DESIRED_ACCESS_FILE_READ_DATA0x00000001For a file object, the right to read the corresponding file data.

For a directory object, the right to read the corresponding directory data.

DESIRED_ACCESS_FILE_ADD_FILE0x00000002For a directory, the right to create a file in the directory.

DESIRED_ACCESS_FILE_WRITE_DATA0x00000002For a file object, the right to write data to the file.

For a directory object, the right to create a file in the directory

DESIRED_ACCESS_FILE_ADD_SUBDIRECTORY0x00000004For a directory, the right to create a subdirectory.

DESIRED_ACCESS_FILE_APPEND_DATA0x00000004For a file object, the right to append data to the file.

(For local files, write operations will not overwrite existing data if this flag is specified without FILE_WRITE_DATA.) For a directory object, the right to create a subdirectory (FILE_ADD_SUBDIRECTORY).

DESIRED_ACCESS_FILE_READ_EA0x00000008The right to read extended file attributes.

DESIRED_ACCESS_FILE_WRITE_EA0x00000010The right to write extended file attributes.

DESIRED_ACCESS_FILE_EXECUTE0x00000020For a native code file, the right to execute the file.

This access right given to scripts may cause the script to be executable, depending on the script interpreter.

DESIRED_ACCESS_FILE_DELETE_CHILD0x00000040For a directory, the right to delete a directory and all the files it contains, including read-only files.

DESIRED_ACCESS_FILE_READ_ATTRIBUTES0x00000080The right to read file attributes.

DESIRED_ACCESS_FILE_WRITE_ATTRIBUTES0x00000100The right to write file attributes.

DESIRED_ACCESS_READ_CONTROL0x00020000The right to read the information in the file or directory object's security descriptor.

This does not include the information in the SACL.

DESIRED_ACCESS_STANDARD_RIGHTS_READ0x00020000Includes READ_CONTROL, which is the right to read the information in the file or directory object's security descriptor.

This does not include the information in the SACL.

DESIRED_ACCESS_STANDARD_RIGHTS_WRITE0x00020000Same as STANDARD_RIGHTS_READ

DESIRED_ACCESS_STANDARD_RIGHTS_EXECUTE0x00020000Same as STANDARD_RIGHTS_READ

DESIRED_ACCESS_SYNCHRONIZE0x00100000The right to use the object for synchronization.

This enables a thread to wait until the object is in the signaled state. Some object types do not support this access right.

DESIRED_ACCESS_FILE_ALL_ACCESS0x001F01FFAll possible access rights for a file.

DESIRED_ACCESS_FILE_GENERIC_READ0x00120089A combinarion of flags that allow reading of the file.

NOTE: Don't match received values against this flag. Instead, use flags that specify the rights that you want to verify or add/remove.

DESIRED_ACCESS_FILE_GENERIC_WRITE0x00120116A combinarion of flags that allow modifications to the file.

NOTE: Don't match received values against this flag. Instead, use flags that specify the rights that you want to verify or add/remove.

DESIRED_ACCESS_FILE_GENERIC_EXECUTE0x001200A0A combinarion of flags that allow execution of the file.

NOTE: Don't match received values against this flag. Instead, use flags that specify the rights that you want to verify or add/remove.

Attributes may contain one or more of the following attributes:

FILE_SYS_ATTR_READ_ONLY0x00000001The file is read-only.

Applications can read the file, but cannot write to it or delete it. This attribute is not honored on directories.

FILE_SYS_ATTR_HIDDEN0x00000002The file or directory is hidden.

The file is not included in an ordinary directory listing.

FILE_SYS_ATTR_SYSTEM0x00000004A file or directory that the operating system uses a part of, or uses exclusively.

FILE_SYS_ATTR_DIRECTORY0x00000010The entry is a directory.

FILE_SYS_ATTR_ARCHIVE0x00000020The entry is an archive file or directory.

Applications typically use this attribute to mark files for backup or removal.

FILE_SYS_ATTR_NORMAL0x00000080A file doesn't have other attributes set.

This attribute is valid only when used alone.

FILE_SYS_ATTR_TEMPORARY0x00000100A file that is being used for temporary storage.

File systems avoid writing data back to mass storage if sufficient cache memory is available, because typically, an application deletes a temporary file after the handle is closed. In that scenario, the system can entirely avoid writing the data. Otherwise, the data are written after the handle is closed.

FILE_SYS_ATTR_SPARSE_FILE0x00000200A file that is a sparse file.

FILE_SYS_ATTR_REPARSE_POINT0x00000400A file that is a reparse point or a symbolic link.

FILE_SYS_ATTR_COMPRESSED0x00000800A file or directory that is compressed.

For a file, all of the data in the file are compressed. For a directory, compression is the default for newly created files and subdirectories. A filesystem implementation can make use of this attribute by setting the support_compressed_attribute property to True and then properly handling the on_get_file_info, on_enumerate_directory, and on_set_file_attributes events.

FILE_SYS_ATTR_OFFLINE0x00001000The data of a file are not available immediately.

This attribute indicates that the file data are physically moved to offline storage.

FILE_SYS_ATTR_NOT_CONTENT_INDEXED0x00002000The file or directory is not to be indexed by the content indexing service.

FILE_SYS_ATTR_ENCRYPTED0x00004000A file or directory that is encrypted.

For a file, all data streams in the file are encrypted. For a directory, encryption is the default for newly created files and subdirectories.

NOTE: This flag is used by NTFS and the OS sends undocumented requests to the filesystem based on this flag. The flag should not be used for files in custom filesystem implementations.

FILE_SYS_ATTR_VIRTUAL0x00010000Reserved.

NOTE: This flag is reserved by the OS and should not be used for files in custom filesystem implementations.

FILE_SYS_ATTR_RECALL_ON_OPEN0x00040000The file or directory has no physical representation on the local system; the item is virtual.

Opening the item will be more expensive than normal (e.g., it will cause at least some of it to be fetched from a remote store). This flag is reported by filesystems during directory enumerations.

ShareMode may contain zero or more of the following share mode flags:

FILESYS_SHARE_READ0x00000001Enables subsequent open operations on a file or device to request read access.

Enables subsequent open operations to request read access; otherwise, no process can open the file or device if it requests read access. If this flag is not specified, but the file or device has been opened for read access, the function fails.

FILESYS_SHARE_WRITE0x00000002Enables subsequent open operations on a file or device to request write access.

Enables subsequent open operations to request write access; otherwise, no process can open the file or device if it requests write access. If this flag is not specified, but the file or device has been opened for write access or has a file mapping with write access, the function fails.

FILESYS_SHARE_DELETE0x00000004Enables subsequent open operations on a file or device to request delete access.

Enables subsequent open operations to request delete access; otherwise, no process can open the file or device if it requests delete access. If this flag is not specified, but the file or device has been opened for delete access, the function fails.

NOTE: Delete access allows both delete and rename operations.

When the file being created or opened is virtual, the event handler must inspect and handle the value of the ShareMode parameter as a filesystem would normally do it.

CreateDisposition may contain one of the following values:

FILE_DISPOSITION_CREATE_NEW0x00000001Creates a new file, only if it does not already exist.

If the specified file exists, the operation fails with an "already exists" error.

FILE_DISPOSITION_CREATE_ALWAYS0x00000002Creates a new file, always.

If the specified file exists and is writable, the system overwrites the file. If the specified file does not exist and is a valid path, a new file is created.

FILE_DISPOSITION_OPEN_EXISTING0x00000003Opens a file, only if it exists

If the specified file does not exist, opening fails.

FILE_DISPOSITION_OPEN_ALWAYS0x00000004Opens a file, always.

If the specified file exists, the operation succeeds. If the specified file does not exist and is a valid path to a writable location, the a file is created.

FILE_DISPOSITION_TRUNCATE_EXISTING0x00000005Opens a file and truncates it so that its size is zero bytes, only if it exists.

If the specified file does not exist, the operation fails with a "file not found" error.

When the file being created or opened is virtual, the event handler must inspect and handle the value of the CreateDisposition parameter as a filesystem would normally do it. This includes adjusting the file size and updating the time attributes depending on the flag. For a virtual file, the driver returns the CreationStatus value that is derived from CreateDisposition as follows:
FILE_DISPOSITION_CREATE_NEW=>CREATION_STATUS_CREATED
FILE_DISPOSITION_CREATE_ALWAYS=>CREATION_STATUS_OVERWRITTEN
FILE_DISPOSITION_OPEN_EXISTING=>CREATION_STATUS_OPENED
FILE_DISPOSITION_OPEN_ALWAYS=>CREATION_STATUS_OPENED
FILE_DISPOSITION_TRUNCATE_EXISTING=>CREATION_STATUS_OVERWRITTEN
If the event handler needs to change the returned CreationStatus, it should change the value of the CreateDisposition to the FILE_DISPOSITION_*** value that leads to the desired CreationStatus value (e.g. set the value to FILE_DISPOSITION_OPEN_EXISTING so that the driver returns CREATION_STATUS_OPENED).

Options contains the flags that are described in the CreateOptions parameter of the Native API's ZwCreateFile function. Most of those flags correspond to flags passed in the FlagsAndAttributes parameter of the Windows API's CreateFile function, but some flags are specific to Native API. If you need those flags, check both functions' descriptions.

Please refer to Microsoft's documentation for detailed information about these constants.

To determine whether the request is for a file or a directory, compare Attributes against the FILE_SYS_ATTR_DIRECTORY constant, as follows: // Check whether the request is for a file or a directory. bool isDirectory = (Attributes & FILE_SYS_ATTR_DIRECTORY) == FILE_SYS_ATTR_DIRECTORY; FILE_SYS_ATTR_DIRECTORY will be present only if it was specified by the calling process; its presence or absence does not indicate the real presence of the attribute on the file or directory on disk.

The attibute may be not present when an existing entry is opened. Thus, the alternative approach is to check the intention of the originator process to open a directory. This is done by verifying whether the Options parameter contains the FILE_DIRECTORY_FILE flag (numeric value 1): // Check whether the request is to open a a directory. bool isDirectory = (Options & 1) != 0; Note that this flag may also be missing, in which case, if the handler needs to know if an existing entry is a file or directory, it should request the attributes of the entry, for example, by opening a direct handle to the entry with the create_file_direct method and using the query_file_information_direct method to obtain the attributes.

To determine whether a file will be deleted when its last handle is closed, compare Options against the Windows API's FILE_FLAG_DELETE_ON_CLOSE constant, as follows: // Check whether the file will be deleted on close. bool deleteOnClose = Options & FILE_FLAG_DELETE_ON_CLOSE == FILE_FLAG_DELETE_ON_CLOSE;

NOTE: Files can be deleted in different ways, so do not use this check to take actions related to tracking file deletion operations. Instead, use the events related to file deletion.

To prevent a file or directory from being opened, set the ResultCode parameter to a non-zero value (typically ERROR_ACCESS_DENIED (5)).

To prevent the OS from creating or opening the file, set the ResultCode parameter to a certain error value, such as ACCESS_DENIED (numeric value is 5).

To encrypt a file, the Encryption and Password parameters are used. Encryption specifies the encryption mode and can initially have, or be set to, one of the following values:

FILEENC_EM_UNDEFINED-1No encryption information specified.

FILEENC_EM_NONE0x0No encryption is applied.

FILEENC_EM_AES256_PBKDF2_HMAC_SHA2560x2Use AES256 encryption with PBKDF2 key derivation based on a HMAC_SHA256 key hash.

If the file does not exist or is recreated (superseded), the Encryption parameter will initially be set to 2, and Password will be empty. If the user does not modify either parameter, the new file will be encrypted with the password specified in the relevant EncryptionRule.

If the user sets the Password parameter as something other than an empty string, the new file will be encrypted using that value. Lastly, if the user sets the Encryption parameter to 0, the new file will not be encrypted.

If the file already exists and is not superseded, the values of these parameters are ignored; the password for the existing file is requested through the on_password_needed event before on_open_file event is fired.

For more information, see Encryption.

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

on_password_needed event

This event fires if a password is needed to open an encrypted file.

Syntax

class CBEncryptPasswordNeededEventParams(object):
  @property
  def file_name() -> str: ...

  @property
  def password() -> str: ...
  @password.setter
  def password(value) -> None: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_password_needed() -> Callable[[CBEncryptPasswordNeededEventParams], None]: ...
@on_password_needed.setter
def on_password_needed(event_hook: Callable[[CBEncryptPasswordNeededEventParams], None]) -> None: ...

Remarks

This event fires when the existing encrypted file specified by FileName is being opened when a valid password has not been provided in the rule. This event will not fire if a valid password has already been provided, or if the file specified by FileName does not exist.

To allow access to the specified file, set the Password parameter to the correct password. To prevent access to the specified file, return the ERROR_ACCESS_DENIED error code via ResultCode.

The event will fire in a loop until a valid password is provided or a nonzero result code is returned.

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

on_progress event

This event fires to indicate the progress of long-running encryption/decryption operations.

Syntax

class CBEncryptProgressEventParams(object):
  @property
  def operation() -> int: ...

  @property
  def file_name() -> str: ...

  @property
  def progress() -> int: ...

  @property
  def total() -> int: ...

  @property
  def can_stop() -> bool: ...

  @property
  def stop() -> bool: ...
  @stop.setter
  def stop(value) -> None: ...

# In class CBEncrypt:
@property
def on_progress() -> Callable[[CBEncryptProgressEventParams], None]: ...
@on_progress.setter
def on_progress(event_hook: Callable[[CBEncryptProgressEventParams], None]) -> None: ...

Remarks

This event fires anytime the class needs to report the progress of a long-running operation, initiated by the application (encrypt_file or decrypt_file). This event can be fired repeatedly during one operation.

The Operation parameter specifies which long-running operation caused this event to fire. Possible values are as follows:

ENC_OP_ENCRYPT1The file is encrypted.

ENC_OP_DECRYPT2The file is decrypted.

The FileName contains the path of the file being processed.

The Progress and Total parameters reflect the current and maximum progress values. Both will be 0 if the operation's progression cannot be determined.

The CanStop parameter indicates whether the application may interrupt the operation by setting the Stop parameter to True.

NOTE: An application should not attempt to call class's methods from handlers of this event. Doing this is guaranteed to cause a deadlock.

on_rename_or_move_file event

This event fires when a file is renamed or moved.

Syntax

class CBEncryptRenameOrMoveFileEventParams(object):
  @property
  def file_name() -> str: ...

  @property
  def new_file_name() -> str: ...

  @property
  def encryption() -> int: ...
  @encryption.setter
  def encryption(value) -> None: ...

  @property
  def password() -> str: ...
  @password.setter
  def password(value) -> None: ...

  @property
  def result_code() -> int: ...
  @result_code.setter
  def result_code(value) -> None: ...

# In class CBEncrypt:
@property
def on_rename_or_move_file() -> Callable[[CBEncryptRenameOrMoveFileEventParams], None]: ...
@on_rename_or_move_file.setter
def on_rename_or_move_file(event_hook: Callable[[CBEncryptRenameOrMoveFileEventParams], None]) -> None: ...

Remarks

This event fires when the file specified by FileName is renamed or moved to another location, identified by NewFileName.

To prevent the OS from renaming the file, set the ResultCode parameter to a certain error value, such as ACCESS_DENIED (numeric value is 5).

The Encryption and Password parameters are used for file encryption. Encryption specifies the encryption mode to use and can have one of the following values:

FILEENC_EM_UNDEFINED-1No encryption information specified.

FILEENC_EM_NONE0x0No encryption is applied.

FILEENC_EM_AES256_PBKDF2_HMAC_SHA2560x2Use AES256 encryption with PBKDF2 key derivation based on a HMAC_SHA256 key hash.

When this event fires, the Encryption parameter indicates whether the source file is currently encrypted (if 2, the file is encrypted), and Password will be empty. If these parameters remain unchanged, the file will not be modified and will retain its original encryption when renamed or moved.

To change the file's encryption, set the Encryption and/or Password parameters accordingly. For example, if a file is initially encrypted when the event fires, Encryption will be 2. Setting Encryption to 0 will decrypt the resulting file, while assigning a new value to Password will re-encrypt the file using the specified password.

Before making any changes, applications may use the file_matches_mask helper method to determine whether the new file name matches an existing encryption rule. This allows the application to adjust the Password parameter as needed to ensure the resulting file uses the appropriate rule password for its new location or name. For example, this can be done by iterating through the encryption_rules collection, and passing the relevant rule path like so:

lock (mEncrypt.EncryptionRules) { foreach (EncryptionRule rule in mEncrypt.EncryptionRules) { if (mEncrypt.FileMatchesMask(rule.Path + "\\*", e.NewFileName, false)) { e.Encryption = 2; e.Password = rule.Password; } } }

Note that before this event fires, if a file is encrypted, the on_password_needed event will fire.

For more information, see Encryption.

The ResultCode parameter will always be 0 when the event is fired. If the event cannot be handled in a "successful" manner for some reason (e.g., a resource is not available or security checks failed), set it to a nonzero value to report an appropriate error. Please see the Error Handling topic for more information.

This event is fired synchronously; please refer to the Event Types topic for more information.

CBEncrypt Config Settings

The class accepts one or more of the following configuration settings. Configuration settings are similar in functionality to properties, but they are rarely used. In order to avoid "polluting" the property namespace of the class, access to these internal properties is provided through the config method.

CBEncrypt Config Settings

DenyUntrustedWrite:   Whether write operations from untrusted processes are blocked.

This configuration setting controls whether the class blocks write operations originating from untrusted processes. By default, this value is enabled. When enabled, processes not listed in the trusted_processes collection will be unable to modify encrypted files. This includes writing data to an existing file, changing the file size, changing the file allocation, and opening a file in modes that would overwrite, truncate, or supersede existing contents.

This behavior ensures that untrusted applications cannot accidentally corrupt encrypted files. Read operations by untrusted processes are still allowed, but they will only see encrypted content.

EncryptAlternateDataStreams:   Whether alternate data streams of files are also encrypted.

This configuration setting controls whether the class should encrypt alternate data streams of files that are covered by encryption rules. When the setting is disabled, only the main (unnamed) data stream of the file is encrypted, but you can still create an encryption rule that will explicitly cover an alternate data stream with a specific name.

LazyEncrypt:   Whether a file is encrypted or decrypted when it is written to or when it is closed.

This configuration setting controls, at which moment encryption or decryption of a file is performed. When the setting is disabled and an existing plain-text file is opened in the mode that permits writing, the driver encrypts or decrypts the file immediately. If the setting is enabled, encryption/decryption does not start until a process starts writing to the file.

By default, this setting is enabled to improve performance.

LoggingEnabled:   Whether extended logging is enabled.

This setting specifies whether extended logging is enabled for this class; it is disabled by default. Please refer to the Error Handling topic for more information.

This setting's value is stored in the registry and is persistent; it requires administrative rights to be changed.

MaxWorkerThreadCount:   The maximum number of worker threads to use to fire events.

This setting specifies the maximum number of worker threads the class may create to fire events on when the serialize_events property is set to seOnMultipleThreads. (If other cases, this setting does not apply.)

By default, this setting is set to 0, and the driver automatically chooses an optimal number of threads using this equation: 4 * number_of_processors where number_of_processors is the number of logical processors, which are virtual cores, i.e. physical processor cores of all available physical processors adjusted by Hyper-Threading (on Intel CPUs) or Simultaneous Multi-Threading (SMT) (on AMD CPUs) .

MinWorkerThreadCount:   The minimum number of worker threads to use to fire events.

This setting specifies the minimum number of worker threads the class should create to fire events on when the serialize_events property is set to seOnMultipleThreads. (In other cases, this setting does not apply.)

By default, this setting is set to 0, and the driver automatically chooses an optimal number of threads using this equation: max(number_of_processors, 4). If this setting's value exceeds the MaxWorkerThreadCount value, the latter is used instead.

NormalizeShortFileNames:   Whether the driver should attempt to resolve short file names and convert them to regular ones.

This configuration setting specifies how the driver should handle short file names in paths that it deals with. The possible values are

  • 0 - never: Do nothing in regard to the short file names.
  • 1 - on local file systems: Causes the driver to attempt to resolve short file names, but only for local filesystems.
  • 2 - always: Causes the driver to attempt to resolve short file names for files on all filesystems.

This setting is global for all instances of the filter with the same Product GUID (the value specified in a call to the install method). If the setting is changed by the application with administrative or equivalent rights, the class stores the value in the HKEY_LOCAL_MACHINE key of the registry. Such stored value can be used with default rules. If the value cannot be stored, it is still used by the driver, but only until the system reboots, so it does not affect default rules activated after the reboot.

If an application uses default rules, it should set this setting right after a successful call to the install method.

Note that this setting only enables the normalization of short names and the use of normalized long names in rule matching; the long name by default is included in the list of names (not on the first position) when the PassAllFileNames setting is enabled. To receive a normalized long name in event handlers when PassAllFileNames is disabled, an application should enable the PassNormalizedShortName configuration setting in addition to this NormalizeShortFileNames setting.

ResolveNtDeviceToDriveLetter:   Whether native device names are translated to drive letters.

This configuration setting specifies whether NT native device names, like \Device\HarddiskVolume1\..., should be translated to DOS-style drive letters, like C:\... when possible. However, please note the following:

  • Such translation will be performed only if a device actually has a corresponding DOS-style drive letter; not all devices do.
  • The on_before_filter_attach_to_volume event always uses NT native device names, because DOS-style drive letters are not assigned until after it fires.

This setting is enabled by default; it can be disabled to improve performance, or if the application needs the native device name.

NOTE: This setting cannot be changed when active is True, and it cannot be changed within events.

WorkerInitialStackSize:   The initial stack size to create worker threads with.

This setting specifies the initial size of the stack each worker thread is created with. The system rounds this value to the nearest page.

By default, this setting is set to 0, and the driver uses a default stack size (currently, 1 MB).

NOTE: This setting cannot be changed when active is True, and it cannot be changed within events.

Base Config Settings

BuildInfo:   Information about the product's build.

When queried, this setting will return a string containing information about the product's build.

LicenseInfo:   Information about the current license.

When queried, this setting will return a string containing information about the license this instance of a class is using. It will return the following information:

  • Product: The product the license is for.
  • Product Key: The key the license was generated from.
  • License Source: Where the license was found (e.g., RuntimeLicense, License File).
  • License Type: The type of license installed (e.g., Royalty Free, Single Server).

CBEncrypt Errors