Filesystem-level encryption (fscrypt)¶
Introduction¶
fscrypt is a library which filesystems can hook into to supporttransparent encryption of files and directories.
Note: “fscrypt” in this document refers to the kernel-level portion,implemented infs/crypto/
, as opposed to the userspace toolfscrypt. This document onlycovers the kernel-level portion. For command-line examples of how touse encryption, see the documentation for the userspace toolfscrypt. Also, it is recommended to usethe fscrypt userspace tool, or other existing userspace tools such asfscryptctl orAndroid’s keymanagement system, overusing the kernel’s API directly. Using existing tools reduces thechance of introducing your own security bugs. (Nevertheless, forcompleteness this documentation covers the kernel’s API anyway.)
Unlike dm-crypt, fscrypt operates at the filesystem level rather thanat the block device level. This allows it to encrypt different fileswith different keys and to have unencrypted files on the samefilesystem. This is useful for multi-user systems where each user’sdata-at-rest needs to be cryptographically isolated from the others.However, except for filenames, fscrypt does not encrypt filesystemmetadata.
Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrateddirectly into supported filesystems --- currently ext4, F2FS, UBIFS,and CephFS. This allows encrypted files to be read and writtenwithout caching both the decrypted and encrypted pages in thepagecache, thereby nearly halving the memory used and bringing it inline with unencrypted files. Similarly, half as many dentries andinodes are needed. eCryptfs also limits encrypted filenames to 143bytes, causing application compatibility issues; fscrypt allows thefull 255 bytes (NAME_MAX). Finally, unlike eCryptfs, the fscrypt APIcan be used by unprivileged users, with no need to mount anything.
fscrypt does not support encrypting files in-place. Instead, itsupports marking an empty directory as encrypted. Then, afteruserspace provides the key, all regular files, directories, andsymbolic links created in that directory tree are transparentlyencrypted.
Threat model¶
Offline attacks¶
Provided that userspace chooses a strong encryption key, fscryptprotects the confidentiality of file contents and filenames in theevent of a single point-in-time permanent offline compromise of theblock device content. fscrypt does not protect the confidentiality ofnon-filename metadata, e.g. file sizes, file permissions, filetimestamps, and extended attributes. Also, the existence and locationof holes (unallocated blocks which logically contain all zeroes) infiles is not protected.
fscrypt is not guaranteed to protect confidentiality or authenticityif an attacker is able to manipulate the filesystem offline prior toan authorized user later accessing the filesystem.
Online attacks¶
fscrypt (and storage encryption in general) can only provide limitedprotection against online attacks. In detail:
Side-channel attacks¶
fscrypt is only resistant to side-channel attacks, such as timing orelectromagnetic attacks, to the extent that the underlying LinuxCryptographic API algorithms or inline encryption hardware are. If avulnerable algorithm is used, such as a table-based implementation ofAES, it may be possible for an attacker to mount a side channel attackagainst the online system. Side channel attacks may also be mountedagainst applications consuming decrypted data.
Unauthorized file access¶
After an encryption key has been added, fscrypt does not hide theplaintext file contents or filenames from other users on the samesystem. Instead, existing access control mechanisms such as file modebits, POSIX ACLs, LSMs, or namespaces should be used for this purpose.
(For the reasoning behind this, understand that while the key isadded, the confidentiality of the data, from the perspective of thesystem itself, isnot protected by the mathematical properties ofencryption but rather only by the correctness of the kernel.Therefore, any encryption-specific access control checks would merelybe enforced by kernelcode and therefore would be largely redundantwith the wide variety of access control mechanisms already available.)
Read-only kernel memory compromise¶
Unlesshardware-wrapped keys are used, an attacker who gains theability to read from arbitrary kernel memory, e.g. by mounting aphysical attack or by exploiting a kernel security vulnerability, cancompromise all fscrypt keys that are currently in-use. This alsoextends to cold boot attacks; if the system is suddenly powered off,keys the system was using may remain in memory for a short time.
However, if hardware-wrapped keys are used, then the fscrypt masterkeys and file contents encryption keys (but not other types of fscryptsubkeys such as filenames encryption keys) are protected fromcompromises of arbitrary kernel memory.
In addition, fscrypt allows encryption keys to be removed from thekernel, which may protect them from later compromise.
In more detail, the FS_IOC_REMOVE_ENCRYPTION_KEY ioctl (or theFS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS ioctl) can wipe a masterencryption key from kernel memory. If it does so, it will also try toevict all cached inodes which had been “unlocked” using the key,thereby wiping their per-file keys and making them once again appear“locked”, i.e. in ciphertext or encrypted form.
However, these ioctls have some limitations:
Per-file keys for in-use files willnot be removed or wiped.Therefore, for maximum effect, userspace should close the relevantencrypted files and directories before removing a master key, aswell as kill any processes whose working directory is in an affectedencrypted directory.
The kernel cannot magically wipe copies of the master key(s) thatuserspace might have as well. Therefore, userspace must wipe allcopies of the master key(s) it makes as well; normally this shouldbe done immediately after FS_IOC_ADD_ENCRYPTION_KEY, without waitingfor FS_IOC_REMOVE_ENCRYPTION_KEY. Naturally, the same also appliesto all higher levels in the key hierarchy. Userspace should alsofollow other security precautions such as
mlock()
ing memorycontaining keys to prevent it from being swapped out.In general, decrypted contents and filenames in the kernel VFScaches are freed but not wiped. Therefore, portions thereof may berecoverable from freed memory, even after the corresponding key(s)were wiped. To partially solve this, you can add init_on_free=1 toyour kernel command line. However, this has a performance cost.
Secret keys might still exist in CPU registers or in other placesnot explicitly considered here.
Full system compromise¶
An attacker who gains “root” access and/or the ability to executearbitrary kernel code can freely exfiltrate data that is protected byany in-use fscrypt keys. Thus, usually fscrypt provides no meaningfulprotection in this scenario. (Data that is protected by a key that isabsent throughout the entire attack remains protected, modulo thelimitations of key removal mentioned above in the case where the keywas removed prior to the attack.)
However, ifhardware-wrapped keys are used, such attackers will beunable to exfiltrate the master keys or file contents keys in a formthat will be usable after the system is powered off. This may beuseful if the attacker is significantly time-limited and/orbandwidth-limited, so they can only exfiltrate some data and need torely on a later offline attack to exfiltrate the rest of it.
Limitations of v1 policies¶
v1 encryption policies have some weaknesses with respect to onlineattacks:
There is no verification that the provided master key is correct.Therefore, a malicious user can temporarily associate the wrong keywith another user’s encrypted files to which they have read-onlyaccess. Because of filesystem caching, the wrong key will then beused by the other user’s accesses to those files, even if the otheruser has the correct key in their own keyring. This violates themeaning of “read-only access”.
A compromise of a per-file key also compromises the master key fromwhich it was derived.
Non-root users cannot securely remove encryption keys.
All the above problems are fixed with v2 encryption policies. Forthis reason among others, it is recommended to use v2 encryptionpolicies on all new encrypted directories.
Key hierarchy¶
Note: this section assumes the use of raw keys rather thanhardware-wrapped keys. The use of hardware-wrapped keys modifies thekey hierarchy slightly. For details, seeHardware-wrapped keys.
Master Keys¶
Each encrypted directory tree is protected by amaster key. Masterkeys can be up to 64 bytes long, and must be at least as long as thegreater of the security strength of the contents and filenamesencryption modes being used. For example, if any AES-256 mode isused, the master key must be at least 256 bits, i.e. 32 bytes. Astricter requirement applies if the key is used by a v1 encryptionpolicy and AES-256-XTS is used; such keys must be 64 bytes.
To “unlock” an encrypted directory tree, userspace must provide theappropriate master key. There can be any number of master keys, eachof which protects any number of directory trees on any number offilesystems.
Master keys must be real cryptographic keys, i.e. indistinguishablefrom random bytestrings of the same length. This implies that usersmust not directly use a password as a master key, zero-pad ashorter key, or repeat a shorter key. Security cannot be guaranteedif userspace makes any such error, as the cryptographic proofs andanalysis would no longer apply.
Instead, users should generate master keys either using acryptographically secure random number generator, or by using a KDF(Key Derivation Function). The kernel does not do any key stretching;therefore, if userspace derives the key from a low-entropy secret suchas a passphrase, it is critical that a KDF designed for this purposebe used, such as scrypt, PBKDF2, or Argon2.
Key derivation function¶
With one exception, fscrypt never uses the master key(s) forencryption directly. Instead, they are only used as input to a KDF(Key Derivation Function) to derive the actual keys.
The KDF used for a particular master key differs depending on whetherthe key is used for v1 encryption policies or for v2 encryptionpolicies. Usersmust not use the same key for both v1 and v2encryption policies. (No real-world attack is currently known on thisspecific case of key reuse, but its security cannot be guaranteedsince the cryptographic proofs and analysis would no longer apply.)
For v1 encryption policies, the KDF only supports deriving per-fileencryption keys. It works by encrypting the master key withAES-128-ECB, using the file’s 16-byte nonce as the AES key. Theresulting ciphertext is used as the derived key. If the ciphertext islonger than needed, then it is truncated to the needed length.
For v2 encryption policies, the KDF is HKDF-SHA512. The master key ispassed as the “input keying material”, no salt is used, and a distinct“application-specific information string” is used for each distinctkey to be derived. For example, when a per-file encryption key isderived, the application-specific information string is the file’snonce prefixed with “fscrypt\0” and a context byte. Differentcontext bytes are used for other types of derived keys.
HKDF-SHA512 is preferred to the original AES-128-ECB based KDF becauseHKDF is more flexible, is nonreversible, and evenly distributesentropy from the master key. HKDF is also standardized and widelyused by other software, whereas the AES-128-ECB based KDF is ad-hoc.
Per-file encryption keys¶
Since each master key can protect many files, it is necessary to“tweak” the encryption of each file so that the same plaintext in twofiles doesn’t map to the same ciphertext, or vice versa. In mostcases, fscrypt does this by deriving per-file keys. When a newencrypted inode (regular file, directory, or symlink) is created,fscrypt randomly generates a 16-byte nonce and stores it in theinode’s encryption xattr. Then, it uses a KDF (as described inKeyderivation function) to derive the file’s key from the master keyand nonce.
Key derivation was chosen over key wrapping because wrapped keys wouldrequire larger xattrs which would be less likely to fit in-line in thefilesystem’s inode table, and there didn’t appear to be anysignificant advantages to key wrapping. In particular, currentlythere is no requirement to support unlocking a file with multiplealternative master keys or to support rotating master keys. Instead,the master keys may be wrapped in userspace, e.g. as is done by thefscrypt tool.
DIRECT_KEY policies¶
The Adiantum encryption mode (seeEncryption modes and usage) issuitable for both contents and filenames encryption, and it acceptslong IVs --- long enough to hold both an 8-byte data unit index and a16-byte per-file nonce. Also, the overhead of each Adiantum key isgreater than that of an AES-256-XTS key.
Therefore, to improve performance and save memory, for Adiantum a“direct key” configuration is supported. When the user has enabledthis by setting FSCRYPT_POLICY_FLAG_DIRECT_KEY in the fscrypt policy,per-file encryption keys are not used. Instead, whenever any data(contents or filenames) is encrypted, the file’s 16-byte nonce isincluded in the IV. Moreover:
For v1 encryption policies, the encryption is done directly with themaster key. Because of this, usersmust not use the same masterkey for any other purpose, even for other v1 policies.
For v2 encryption policies, the encryption is done with a per-modekey derived using the KDF. Users may use the same master key forother v2 encryption policies.
IV_INO_LBLK_64 policies¶
When FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 is set in the fscrypt policy,the encryption keys are derived from the master key, encryption modenumber, and filesystem UUID. This normally results in all filesprotected by the same master key sharing a single contents encryptionkey and a single filenames encryption key. To still encrypt differentfiles’ data differently, inode numbers are included in the IVs.Consequently, shrinking the filesystem may not be allowed.
This format is optimized for use with inline encryption hardwarecompliant with the UFS standard, which supports only 64 IV bits perI/O request and may have only a small number of keyslots.
IV_INO_LBLK_32 policies¶
IV_INO_LBLK_32 policies work like IV_INO_LBLK_64, except that forIV_INO_LBLK_32, the inode number is hashed with SipHash-2-4 (where theSipHash key is derived from the master key) and added to the file dataunit index mod 2^32 to produce a 32-bit IV.
This format is optimized for use with inline encryption hardwarecompliant with the eMMC v5.2 standard, which supports only 32 IV bitsper I/O request and may have only a small number of keyslots. Thisformat results in some level of IV reuse, so it should only be usedwhen necessary due to hardware limitations.
Key identifiers¶
For master keys used for v2 encryption policies, a unique 16-byte “keyidentifier” is also derived using the KDF. This value is stored inthe clear, since it is needed to reliably identify the key itself.
Dirhash keys¶
For directories that are indexed using a secret-keyed dirhash over theplaintext filenames, the KDF is also used to derive a 128-bitSipHash-2-4 key per directory in order to hash filenames. This worksjust like deriving a per-file encryption key, except that a differentKDF context is used. Currently, only casefolded (“case-insensitive”)encrypted directories use this style of hashing.
Encryption modes and usage¶
fscrypt allows one encryption mode to be specified for file contentsand one encryption mode to be specified for filenames. Differentdirectory trees are permitted to use different encryption modes.
Supported modes¶
Currently, the following pairs of encryption modes are supported:
AES-256-XTS for contents and AES-256-CBC-CTS for filenames
AES-256-XTS for contents and AES-256-HCTR2 for filenames
Adiantum for both contents and filenames
AES-128-CBC-ESSIV for contents and AES-128-CBC-CTS for filenames
SM4-XTS for contents and SM4-CBC-CTS for filenames
Note: in the API, “CBC” means CBC-ESSIV, and “CTS” means CBC-CTS.So, for example, FSCRYPT_MODE_AES_256_CTS means AES-256-CBC-CTS.
Authenticated encryption modes are not currently supported because ofthe difficulty of dealing with ciphertext expansion. Therefore,contents encryption uses a block cipher inXTS mode orCBC-ESSIV mode,or a wide-block cipher. Filenames encryption uses ablock cipher inCBC-CTS mode or a wide-blockcipher.
The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default.It is also the only option that isguaranteed to always be supportedif the kernel supports fscrypt at all; seeKernel config options.
The (AES-256-XTS, AES-256-HCTR2) pair is also a good choice thatupgrades the filenames encryption to use a wide-block cipher. (Awide-block cipher, also called a tweakable super-pseudorandompermutation, has the property that changing one bit scrambles theentire result.) As described inFilenames encryption, a wide-blockcipher is the ideal mode for the problem domain, though CBC-CTS is the“least bad” choice among the alternatives. For more information aboutHCTR2, seethe HCTR2 paper.
Adiantum is recommended on systems where AES is too slow due to lackof hardware acceleration for AES. Adiantum is a wide-block cipherthat uses XChaCha12 and AES-256 as its underlying components. Most ofthe work is done by XChaCha12, which is much faster than AES when AESacceleration is unavailable. For more information about Adiantum, seethe Adiantum paper.
The (AES-128-CBC-ESSIV, AES-128-CBC-CTS) pair was added to try toprovide a more efficient option for systems that lack AES instructionsin the CPU but do have a non-inline crypto engine such as CAAM or CESAthat supports AES-CBC (and not AES-XTS). This is deprecated. It hasbeen shown that just doing AES on the CPU is actually faster.Moreover, Adiantum is faster still and is recommended on such systems.
The remaining mode pairs are the “national pride ciphers”:
(SM4-XTS, SM4-CBC-CTS)
Generally speaking, these ciphers aren’t “bad” per se, but theyreceive limited security review compared to the usual choices such asAES and ChaCha. They also don’t bring much new to the table. It issuggested to only use these ciphers where their use is mandated.
Kernel config options¶
Enabling fscrypt support (CONFIG_FS_ENCRYPTION) automatically pulls inonly the basic support from the crypto API needed to use AES-256-XTSand AES-256-CBC-CTS encryption. For optimal performance, it isstrongly recommended to also enable any available platform-specifickconfig options that provide acceleration for the algorithm(s) youwish to use. Support for any “non-default” encryption modes typicallyrequires extra kconfig options as well.
Below, some relevant options are listed by encryption mode. Note,acceleration options not listed below may be available for yourplatform; refer to the kconfig menus. File contents encryption canalso be configured to use inline encryption hardware instead of thekernel crypto API (seeInline encryption support); in that case,the file contents mode doesn’t need to supported in the kernel cryptoAPI, but the filenames mode still does.
- AES-256-XTS and AES-256-CBC-CTS
- Recommended:
arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
x86: CONFIG_CRYPTO_AES_NI_INTEL
- AES-256-HCTR2
- Mandatory:
CONFIG_CRYPTO_HCTR2
- Recommended:
arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
arm64: CONFIG_CRYPTO_POLYVAL_ARM64_CE
x86: CONFIG_CRYPTO_AES_NI_INTEL
x86: CONFIG_CRYPTO_POLYVAL_CLMUL_NI
- Adiantum
- Mandatory:
CONFIG_CRYPTO_ADIANTUM
- Recommended:
arm32: CONFIG_CRYPTO_NHPOLY1305_NEON
arm64: CONFIG_CRYPTO_NHPOLY1305_NEON
x86: CONFIG_CRYPTO_NHPOLY1305_SSE2
x86: CONFIG_CRYPTO_NHPOLY1305_AVX2
- AES-128-CBC-ESSIV and AES-128-CBC-CTS:
- Mandatory:
CONFIG_CRYPTO_ESSIV
CONFIG_CRYPTO_SHA256 or another SHA-256 implementation
- Recommended:
AES-CBC acceleration
Contents encryption¶
For contents encryption, each file’s contents is divided into “dataunits”. Each data unit is encrypted independently. The IV for eachdata unit incorporates the zero-based index of the data unit withinthe file. This ensures that each data unit within a file is encrypteddifferently, which is essential to prevent leaking information.
Note: the encryption depending on the offset into the file means thatoperations like “collapse range” and “insert range” that rearrange theextent mapping of files are not supported on encrypted files.
There are two cases for the sizes of the data units:
Fixed-size data units. This is how all filesystems other than UBIFSwork. A file’s data units are all the same size; the last data unitis zero-padded if needed. By default, the data unit size is equalto the filesystem block size. On some filesystems, users can selecta sub-block data unit size via the
log2_data_unit_size
field ofthe encryption policy; seeFS_IOC_SET_ENCRYPTION_POLICY.Variable-size data units. This is what UBIFS does. Each “UBIFSdata node” is treated as a crypto data unit. Each contains variablelength, possibly compressed data, zero-padded to the next 16-byteboundary. Users cannot select a sub-block data unit size on UBIFS.
In the case of compression + encryption, the compressed data isencrypted. UBIFS compression works as described above. f2fscompression works a bit differently; it compresses a number offilesystem blocks into a smaller number of filesystem blocks.Therefore a f2fs-compressed file still uses fixed-size data units, andit is encrypted in a similar way to a file containing holes.
As mentioned inKey hierarchy, the default encryption setting usesper-file keys. In this case, the IV for each data unit is simply theindex of the data unit in the file. However, users can select anencryption setting that does not use per-file keys. For these, somekind of file identifier is incorporated into the IVs as follows:
WithDIRECT_KEY policies, the data unit index is placed in bits0-63 of the IV, and the file’s nonce is placed in bits 64-191.
WithIV_INO_LBLK_64 policies, the data unit index is placed inbits 0-31 of the IV, and the file’s inode number is placed in bits32-63. This setting is only allowed when data unit indices andinode numbers fit in 32 bits.
WithIV_INO_LBLK_32 policies, the file’s inode number is hashedand added to the data unit index. The resulting value is truncatedto 32 bits and placed in bits 0-31 of the IV. This setting is onlyallowed when data unit indices and inode numbers fit in 32 bits.
The byte order of the IV is always little endian.
If the user selects FSCRYPT_MODE_AES_128_CBC for the contents mode, anESSIV layer is automatically included. In this case, before the IV ispassed to AES-128-CBC, it is encrypted with AES-256 where the AES-256key is the SHA-256 hash of the file’s contents encryption key.
Filenames encryption¶
For filenames, each full filename is encrypted at once. Because ofthe requirements to retain support for efficient directory lookups andfilenames of up to 255 bytes, the same IV is used for every filenamein a directory.
However, each encrypted directory still uses a unique key, oralternatively has the file’s nonce (forDIRECT_KEY policies) orinode number (forIV_INO_LBLK_64 policies) included in the IVs.Thus, IV reuse is limited to within a single directory.
With CBC-CTS, the IV reuse means that when the plaintext filenames share acommon prefix at least as long as the cipher block size (16 bytes for AES), thecorresponding encrypted filenames will also share a common prefix. This isundesirable. Adiantum and HCTR2 do not have this weakness, as they arewide-block encryption modes.
All supported filenames encryption modes accept any plaintext length>= 16 bytes; cipher block alignment is not required. However,filenames shorter than 16 bytes are NUL-padded to 16 bytes beforebeing encrypted. In addition, to reduce leakage of filename lengthsvia their ciphertexts, all filenames are NUL-padded to the next 4, 8,16, or 32-byte boundary (configurable). 32 is recommended since thisprovides the best confidentiality, at the cost of making directoryentries consume slightly more space. Note that since NUL (\0
) isnot otherwise a valid character in filenames, the padding will neverproduce duplicate plaintexts.
Symbolic link targets are considered a type of filename and areencrypted in the same way as filenames in directory entries, exceptthat IV reuse is not a problem as each symlink has its own inode.
User API¶
Setting an encryption policy¶
FS_IOC_SET_ENCRYPTION_POLICY¶
The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on anempty directory or verifies that a directory or regular file alreadyhas the specified encryption policy. It takes in a pointer tostructfscrypt_policy_v1
orstructfscrypt_policy_v2
, defined asfollows:
#define FSCRYPT_POLICY_V1 0#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8struct fscrypt_policy_v1 { __u8 version; __u8 contents_encryption_mode; __u8 filenames_encryption_mode; __u8 flags; __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];};#define fscrypt_policy fscrypt_policy_v1#define FSCRYPT_POLICY_V2 2#define FSCRYPT_KEY_IDENTIFIER_SIZE 16struct fscrypt_policy_v2 { __u8 version; __u8 contents_encryption_mode; __u8 filenames_encryption_mode; __u8 flags; __u8 log2_data_unit_size; __u8 __reserved[3]; __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];};
This structure must be initialized as follows:
version
must be FSCRYPT_POLICY_V1 (0) ifstructfscrypt_policy_v1
is used or FSCRYPT_POLICY_V2 (2) ifstructfscrypt_policy_v2
is used. (Note: we refer to the originalpolicy version as “v1”, though its version code is really 0.)For new encrypted directories, use v2 policies.contents_encryption_mode
andfilenames_encryption_mode
mustbe set to constants from<linux/fscrypt.h>
which identify theencryption modes to use. If unsure, use FSCRYPT_MODE_AES_256_XTS(1) forcontents_encryption_mode
and FSCRYPT_MODE_AES_256_CTS(4) forfilenames_encryption_mode
. For details, seeEncryptionmodes and usage.v1 encryption policies only support three combinations of modes:(FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS),(FSCRYPT_MODE_AES_128_CBC, FSCRYPT_MODE_AES_128_CTS), and(FSCRYPT_MODE_ADIANTUM, FSCRYPT_MODE_ADIANTUM). v2 policies supportall combinations documented inSupported modes.
flags
contains optional flags from<linux/fscrypt.h>
:FSCRYPT_POLICY_FLAGS_PAD_*: The amount of NUL padding to use whenencrypting filenames. If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32(0x3).
FSCRYPT_POLICY_FLAG_DIRECT_KEY: SeeDIRECT_KEY policies.
FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: SeeIV_INO_LBLK_64policies.
FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: SeeIV_INO_LBLK_32policies.
v1 encryption policies only support the PAD_* and DIRECT_KEY flags.The other flags are only supported by v2 encryption policies.
The DIRECT_KEY, IV_INO_LBLK_64, and IV_INO_LBLK_32 flags aremutually exclusive.
log2_data_unit_size
is the log2 of the data unit size in bytes,or 0 to select the default data unit size. The data unit size isthe granularity of file contents encryption. For example, settinglog2_data_unit_size
to 12 causes file contents be passed to theunderlying encryption algorithm (such as AES-256-XTS) in 4096-bytedata units, each with its own IV.Not all filesystems support setting
log2_data_unit_size
. ext4and f2fs support it since Linux v6.7. On filesystems that supportit, the supported nonzero values are 9 through the log2 of thefilesystem block size, inclusively. The default value of 0 selectsthe filesystem block size.The main use case for
log2_data_unit_size
is for selecting adata unit size smaller than the filesystem block size forcompatibility with inline encryption hardware that only supportssmaller data unit sizes./sys/block/$disk/queue/crypto/
may beuseful for checking which data unit sizes are supported by aparticular system’s inline encryption hardware.Leave this field zeroed unless you are certain you need it. Usingan unnecessarily small data unit size reduces performance.
For v2 encryption policies,
__reserved
must be zeroed.For v1 encryption policies,
master_key_descriptor
specifies howto find the master key in a keyring; seeAdding keys. It is upto userspace to choose a uniquemaster_key_descriptor
for eachmaster key. The e4crypt and fscrypt tools use the first 8 bytes ofSHA-512(SHA-512(master_key))
, but this particular scheme is notrequired. Also, the master key need not be in the keyring yet whenFS_IOC_SET_ENCRYPTION_POLICY is executed. However, it must be addedbefore any files can be created in the encrypted directory.For v2 encryption policies,
master_key_descriptor
has beenreplaced withmaster_key_identifier
, which is longer and cannotbe arbitrarily chosen. Instead, the key must first be added usingFS_IOC_ADD_ENCRYPTION_KEY. Then, thekey_spec.u.identifier
the kernel returned in thestructfscrypt_add_key_arg
mustbe used as themaster_key_identifier
instructfscrypt_policy_v2
.
If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICYverifies that the file is an empty directory. If so, the specifiedencryption policy is assigned to the directory, turning it into anencrypted directory. After that, and after providing thecorresponding master key as described inAdding keys, all regularfiles, directories (recursively), and symlinks created in thedirectory will be encrypted, inheriting the same encryption policy.The filenames in the directory’s entries will be encrypted as well.
Alternatively, if the file is already encrypted, thenFS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryptionpolicy exactly matches the actual one. If they match, then the ioctlreturns 0. Otherwise, it fails with EEXIST. This works on bothregular files and directories, including nonempty directories.
When a v2 encryption policy is assigned to a directory, it is alsorequired that either the specified key has been added by the currentuser or that the caller has CAP_FOWNER in the initial user namespace.(This is needed to prevent a user from encrypting their data withanother user’s key.) The key must remain added whileFS_IOC_SET_ENCRYPTION_POLICY is executing. However, if the newencrypted directory does not need to be accessed immediately, then thekey can be removed right away afterwards.
Note that the ext4 filesystem does not allow the root directory to beencrypted, even if it is empty. Users who want to encrypt an entirefilesystem with one key should consider using dm-crypt instead.
FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:
EACCES
: the file is not owned by the process’s uid, nor does theprocess have the CAP_FOWNER capability in a namespace with the fileowner’s uid mappedEEXIST
: the file is already encrypted with an encryption policydifferent from the one specifiedEINVAL
: an invalid encryption policy was specified (invalidversion, mode(s), or flags; or reserved bits were set); or a v1encryption policy was specified but the directory has the casefoldflag enabled (casefolding is incompatible with v1 policies).ENOKEY
: a v2 encryption policy was specified, but the key withthe specifiedmaster_key_identifier
has not been added, nor doesthe process have the CAP_FOWNER capability in the initial usernamespaceENOTDIR
: the file is unencrypted and is a regular file, not adirectoryENOTEMPTY
: the file is unencrypted and is a nonempty directoryENOTTY
: this type of filesystem does not implement encryptionEOPNOTSUPP
: the kernel was not configured with encryptionsupport for filesystems, or the filesystem superblock has nothad encryption enabled on it. (For example, to use encryption on anext4 filesystem, CONFIG_FS_ENCRYPTION must be enabled in thekernel config, and the superblock must have had the “encrypt”feature flag enabled usingtune2fs-Oencrypt
ormkfs.ext4-Oencrypt
.)EPERM
: this directory may not be encrypted, e.g. because it isthe root directory of an ext4 filesystemEROFS
: the filesystem is readonly
Getting an encryption policy¶
Two ioctls are available to get a file’s encryption policy:
The extended (_EX) version of the ioctl is more general and isrecommended to use when possible. However, on older kernels only theoriginal ioctl is available. Applications should try the extendedversion, and if it fails with ENOTTY fall back to the originalversion.
FS_IOC_GET_ENCRYPTION_POLICY_EX¶
The FS_IOC_GET_ENCRYPTION_POLICY_EX ioctl retrieves the encryptionpolicy, if any, for a directory or regular file. No additionalpermissions are required beyond the ability to open the file. Ittakes in a pointer tostructfscrypt_get_policy_ex_arg
,defined as follows:
struct fscrypt_get_policy_ex_arg { __u64 policy_size; /* input/output */ union { __u8 version; struct fscrypt_policy_v1 v1; struct fscrypt_policy_v2 v2; } policy; /* output */};
The caller must initializepolicy_size
to the size available forthe policy struct, i.e.sizeof(arg.policy)
.
On success, the policystructis
returned inpolicy
, and itsactual size is returned inpolicy_size
.policy.version
shouldbe checked to determine the version of policy returned. Note that theversion code for the “v1” policy is actually 0 (FSCRYPT_POLICY_V1).
FS_IOC_GET_ENCRYPTION_POLICY_EX can fail with the following errors:
EINVAL
: the file is encrypted, but it uses an unrecognizedencryption policy versionENODATA
: the file is not encryptedENOTTY
: this type of filesystem does not implement encryption,or this kernel is too old to support FS_IOC_GET_ENCRYPTION_POLICY_EX(try FS_IOC_GET_ENCRYPTION_POLICY instead)EOPNOTSUPP
: the kernel was not configured with encryptionsupport for this filesystem, or the filesystem superblock has nothad encryption enabled on itEOVERFLOW
: the file is encrypted and uses a recognizedencryption policy version, but the policystructdoes
not fit intothe provided buffer
Note: if you only need to know whether a file is encrypted or not, onmost filesystems it is also possible to use the FS_IOC_GETFLAGS ioctland check for FS_ENCRYPT_FL, or to use thestatx()
system call andcheck for STATX_ATTR_ENCRYPTED in stx_attributes.
FS_IOC_GET_ENCRYPTION_POLICY¶
The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve theencryption policy, if any, for a directory or regular file. However,unlikeFS_IOC_GET_ENCRYPTION_POLICY_EX,FS_IOC_GET_ENCRYPTION_POLICY only supports the original policyversion. It takes in a pointer directly tostructfscrypt_policy_v1
rather thanstructfscrypt_get_policy_ex_arg
.
The error codes for FS_IOC_GET_ENCRYPTION_POLICY are the same as thosefor FS_IOC_GET_ENCRYPTION_POLICY_EX, except thatFS_IOC_GET_ENCRYPTION_POLICY also returnsEINVAL
if the file isencrypted using a newer encryption policy version.
Getting the per-filesystem salt¶
Some filesystems, such as ext4 and F2FS, also support the deprecatedioctl FS_IOC_GET_ENCRYPTION_PWSALT. This ioctl retrieves a randomlygenerated 16-byte value stored in the filesystem superblock. Thisvalue is intended to used as a salt when deriving an encryption keyfrom a passphrase or other low-entropy user credential.
FS_IOC_GET_ENCRYPTION_PWSALT is deprecated. Instead, prefer togenerate and manage any needed salt(s) in userspace.
Getting a file’s encryption nonce¶
Since Linux v5.7, the ioctl FS_IOC_GET_ENCRYPTION_NONCE is supported.On encrypted files and directories it gets the inode’s 16-byte nonce.On unencrypted files and directories, it fails with ENODATA.
This ioctl can be useful for automated tests which verify that theencryption is being done correctly. It is not needed for normal useof fscrypt.
Adding keys¶
FS_IOC_ADD_ENCRYPTION_KEY¶
The FS_IOC_ADD_ENCRYPTION_KEY ioctl adds a master encryption key tothe filesystem, making all files on the filesystem which wereencrypted using that key appear “unlocked”, i.e. in plaintext form.It can be executed on any file or directory on the target filesystem,but using the filesystem’s root directory is recommended. It takes ina pointer tostructfscrypt_add_key_arg
, defined as follows:
struct fscrypt_add_key_arg { struct fscrypt_key_specifier key_spec; __u32 raw_size; __u32 key_id;#define FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED 0x00000001 __u32 flags; __u32 __reserved[7]; __u8 raw[];};#define FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR 1#define FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER 2struct fscrypt_key_specifier { __u32 type; /* one of FSCRYPT_KEY_SPEC_TYPE_* */ __u32 __reserved; union { __u8 __reserved[32]; /* reserve some extra space */ __u8 descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE]; __u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE]; } u;};struct fscrypt_provisioning_key_payload { __u32 type; __u32 flags; __u8 raw[];};
structfscrypt_add_key_arg
must be zeroed, then initializedas follows:
If the key is being added for use by v1 encryption policies, then
key_spec.type
must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, andkey_spec.u.descriptor
must contain the descriptor of the keybeing added, corresponding to the value in themaster_key_descriptor
field ofstructfscrypt_policy_v1
.To add this type of key, the calling process must have theCAP_SYS_ADMIN capability in the initial user namespace.Alternatively, if the key is being added for use by v2 encryptionpolicies, then
key_spec.type
must containFSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, andkey_spec.u.identifier
isanoutput field which the kernel fills in with a cryptographichash of the key. To add this type of key, the calling process doesnot need any privileges. However, the number of keys that can beadded is limited by the user’s quota for the keyrings service (seeDocumentation/security/keys/core.rst
).raw_size
must be the size of theraw
key provided, in bytes.Alternatively, ifkey_id
is nonzero, this field must be 0, sincein that case the size is implied by the specified Linux keyring key.key_id
is 0 if the key is given directly in theraw
field.Otherwisekey_id
is the ID of a Linux keyring key of type“fscrypt-provisioning” whose payload isstructfscrypt_provisioning_key_payload
whoseraw
field contains thekey, whosetype
field matcheskey_spec.type
, and whoseflags
field matchesflags
. Sinceraw
isvariable-length, the total size of this key’s payload must besizeof(structfscrypt_provisioning_key_payload)
plus the numberof key bytes. The process must have Search permission on this key.Most users should leave this 0 and specify the key directly. Thesupport for specifying a Linux keyring key is intended mainly toallow re-adding keys after a filesystem is unmounted and re-mounted,without having to store the keys in userspace memory.
flags
contains optional flags from<linux/fscrypt.h>
:FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED: This denotes that the key is ahardware-wrapped key. SeeHardware-wrapped keys. This flagcan’t be used if FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR is used.
raw
is a variable-length field which must contain the actualkey,raw_size
bytes long. Alternatively, ifkey_id
isnonzero, then this field is unused. Note that despite being namedraw
, if FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED is specified then itwill contain a wrapped key, not a raw key.
For v2 policy keys, the kernel keeps track of which user (identifiedby effective user ID) added the key, and only allows the key to beremoved by that user --- or by “root”, if they useFS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS.
However, if another user has added the key, it may be desirable toprevent that other user from unexpectedly removing it. Therefore,FS_IOC_ADD_ENCRYPTION_KEY may also be used to add a v2 policy keyagain, even if it’s already added by other user(s). In this case,FS_IOC_ADD_ENCRYPTION_KEY will just install a claim to the key for thecurrent user, rather than actually add the key again (but the key muststill be provided, as a proof of knowledge).
FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim tothe key was either added or already exists.
FS_IOC_ADD_ENCRYPTION_KEY can fail with the following errors:
EACCES
: FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR was specified, but thecaller does not have the CAP_SYS_ADMIN capability in the initialuser namespace; or the key was specified by Linux key ID but theprocess lacks Search permission on the key.EBADMSG
: invalid hardware-wrapped keyEDQUOT
: the key quota for this user would be exceeded by addingthe keyEINVAL
: invalid key size or key specifier type, or reserved bitswere setEKEYREJECTED
: the key was specified by Linux key ID, but the keyhas the wrong typeENOKEY
: the key was specified by Linux key ID, but no key existswith that IDENOTTY
: this type of filesystem does not implement encryptionEOPNOTSUPP
: the kernel was not configured with encryptionsupport for this filesystem, or the filesystem superblock has nothad encryption enabled on it; or a hardware wrapped key was specifiedbut the filesystem does not support inline encryption or the hardwaredoes not support hardware-wrapped keys
Legacy method¶
For v1 encryption policies, a master encryption key can also beprovided by adding it to a process-subscribed keyring, e.g. to asession keyring, or to a user keyring if the user keyring is linkedinto the session keyring.
This method is deprecated (and not supported for v2 encryptionpolicies) for several reasons. First, it cannot be used incombination with FS_IOC_REMOVE_ENCRYPTION_KEY (seeRemoving keys),so for removing a key a workaround such askeyctl_unlink()
incombination withsync;echo2>/proc/sys/vm/drop_caches
wouldhave to be used. Second, it doesn’t match the fact that thelocked/unlocked status of encrypted files (i.e. whether they appear tobe in plaintext form or in ciphertext form) is global. This mismatchhas caused much confusion as well as real problems when processesrunning under different UIDs, such as asudo
command, need toaccess encrypted files.
Nevertheless, to add a key to one of the process-subscribed keyrings,theadd_key()
system call can be used (see:Documentation/security/keys/core.rst
). The key type must be“logon”; keys of this type are kept in kernel memory and cannot beread back by userspace. The key description must be “fscrypt:”followed by the 16-character lower case hex representation of themaster_key_descriptor
that was set in the encryption policy. Thekey payload must conform to the following structure:
#define FSCRYPT_MAX_KEY_SIZE 64struct fscrypt_key { __u32 mode; __u8 raw[FSCRYPT_MAX_KEY_SIZE]; __u32 size;};
mode
is ignored; just set it to 0. The actual key is provided inraw
withsize
indicating its size in bytes. That is, thebytesraw[0..size-1]
(inclusive) are the actual key.
The key description prefix “fscrypt:” may alternatively be replacedwith a filesystem-specific prefix such as “ext4:”. However, thefilesystem-specific prefixes are deprecated and should not be used innew programs.
Removing keys¶
Two ioctls are available for removing a key that was added byFS_IOC_ADD_ENCRYPTION_KEY:
These two ioctls differ only in cases where v2 policy keys are addedor removed by non-root users.
These ioctls don’t work on keys that were added via the legacyprocess-subscribed keyrings mechanism.
Before using these ioctls, read theOnline attacks section for adiscussion of the security goals and limitations of these ioctls.
FS_IOC_REMOVE_ENCRYPTION_KEY¶
The FS_IOC_REMOVE_ENCRYPTION_KEY ioctl removes a claim to a masterencryption key from the filesystem, and possibly removes the keyitself. It can be executed on any file or directory on the targetfilesystem, but using the filesystem’s root directory is recommended.It takes in a pointer tostructfscrypt_remove_key_arg
, definedas follows:
struct fscrypt_remove_key_arg { struct fscrypt_key_specifier key_spec;#define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY 0x00000001#define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS 0x00000002 __u32 removal_status_flags; /* output */ __u32 __reserved[5];};
This structure must be zeroed, then initialized as follows:
The key to remove is specified by
key_spec
:To remove a key used by v1 encryption policies, set
key_spec.type
to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fillinkey_spec.u.descriptor
. To remove this type of key, thecalling process must have the CAP_SYS_ADMIN capability in theinitial user namespace.To remove a key used by v2 encryption policies, set
key_spec.type
to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fillinkey_spec.u.identifier
.
For v2 policy keys, this ioctl is usable by non-root users. However,to make this possible, it actually just removes the current user’sclaim to the key, undoing a single call to FS_IOC_ADD_ENCRYPTION_KEY.Only after all claims are removed is the key really removed.
For example, if FS_IOC_ADD_ENCRYPTION_KEY was called with uid 1000,then the key will be “claimed” by uid 1000, andFS_IOC_REMOVE_ENCRYPTION_KEY will only succeed as uid 1000. Or, ifboth uids 1000 and 2000 added the key, then for each uidFS_IOC_REMOVE_ENCRYPTION_KEY will only remove their own claim. Onlyonceboth are removed is the key really removed. (Think of it likeunlinking a file that may have hard links.)
If FS_IOC_REMOVE_ENCRYPTION_KEY really removes the key, it will alsotry to “lock” all files that had been unlocked with the key. It won’tlock files that are still in-use, so this ioctl is expected to be usedin cooperation with userspace ensuring that none of the files arestill open. However, if necessary, this ioctl can be executed againlater to retry locking any remaining files.
FS_IOC_REMOVE_ENCRYPTION_KEY returns 0 if either the key was removed(but may still have files remaining to be locked), the user’s claim tothe key was removed, or the key was already removed but had filesremaining to be the locked so the ioctl retried locking them. In anyof these cases,removal_status_flags
is filled in with thefollowing informational status flags:
FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY
: set if some file(s)are still in-use. Not guaranteed to be set in the case where onlythe user’s claim to the key was removed.FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS
: set if only theuser’s claim to the key was removed, not the key itself
FS_IOC_REMOVE_ENCRYPTION_KEY can fail with the following errors:
EACCES
: The FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR key specifier typewas specified, but the caller does not have the CAP_SYS_ADMINcapability in the initial user namespaceEINVAL
: invalid key specifier type, or reserved bits were setENOKEY
: the key object was not found at all, i.e. it was neveradded in the first place or was already fully removed including allfiles locked; or, the user does not have a claim to the key (butsomeone else does).ENOTTY
: this type of filesystem does not implement encryptionEOPNOTSUPP
: the kernel was not configured with encryptionsupport for this filesystem, or the filesystem superblock has nothad encryption enabled on it
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS¶
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same asFS_IOC_REMOVE_ENCRYPTION_KEY, except that for v2 policy keys, theALL_USERS version of the ioctl will remove all users’ claims to thekey, not just the current user’s. I.e., the key itself will always beremoved, no matter how many users have added it. This difference isonly meaningful if non-root users are adding and removing keys.
Because of this, FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS also requires“root”, namely the CAP_SYS_ADMIN capability in the initial usernamespace. Otherwise it will fail with EACCES.
Getting key status¶
FS_IOC_GET_ENCRYPTION_KEY_STATUS¶
The FS_IOC_GET_ENCRYPTION_KEY_STATUS ioctl retrieves the status of amaster encryption key. It can be executed on any file or directory onthe target filesystem, but using the filesystem’s root directory isrecommended. It takes in a pointer tostructfscrypt_get_key_status_arg
, defined as follows:
struct fscrypt_get_key_status_arg { /* input */ struct fscrypt_key_specifier key_spec; __u32 __reserved[6]; /* output */#define FSCRYPT_KEY_STATUS_ABSENT 1#define FSCRYPT_KEY_STATUS_PRESENT 2#define FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED 3 __u32 status;#define FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF 0x00000001 __u32 status_flags; __u32 user_count; __u32 __out_reserved[13];};
The caller must zero all input fields, then fill inkey_spec
:
To get the status of a key for v1 encryption policies, set
key_spec.type
to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fillinkey_spec.u.descriptor
.To get the status of a key for v2 encryption policies, set
key_spec.type
to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fillinkey_spec.u.identifier
.
On success, 0 is returned and the kernel fills in the output fields:
status
indicates whether the key is absent, present, orincompletely removed. Incompletely removed means that removal hasbeen initiated, but some files are still in use; i.e.,FS_IOC_REMOVE_ENCRYPTION_KEY returned 0 but set the informationalstatus flag FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY.status_flags
can contain the following flags:FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF
indicates that the keyhas added by the current user. This is only set for keysidentified byidentifier
rather than bydescriptor
.
user_count
specifies the number of users who have added the key.This is only set for keys identified byidentifier
rather thanbydescriptor
.
FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:
EINVAL
: invalid key specifier type, or reserved bits were setENOTTY
: this type of filesystem does not implement encryptionEOPNOTSUPP
: the kernel was not configured with encryptionsupport for this filesystem, or the filesystem superblock has nothad encryption enabled on it
Among other use cases, FS_IOC_GET_ENCRYPTION_KEY_STATUS can be usefulfor determining whether the key for a given encrypted directory needsto be added before prompting the user for the passphrase needed toderive the key.
FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys inthe filesystem-level keyring, i.e. the keyring managed byFS_IOC_ADD_ENCRYPTION_KEY andFS_IOC_REMOVE_ENCRYPTION_KEY. Itcannot get the status of a key that has only been added for use by v1encryption policies using the legacy mechanism involvingprocess-subscribed keyrings.
Access semantics¶
With the key¶
With the encryption key, encrypted regular files, directories, andsymlinks behave very similarly to their unencrypted counterparts ---after all, the encryption is intended to be transparent. However,astute users may notice some differences in behavior:
Unencrypted files, or files encrypted with a different encryptionpolicy (i.e. different key, modes, or flags), cannot be renamed orlinked into an encrypted directory; seeEncryption policyenforcement. Attempts to do so will fail with EXDEV. However,encrypted files can be renamed within an encrypted directory, orinto an unencrypted directory.
Note: “moving” an unencrypted file into an encrypted directory, e.g.with themv program, is implemented in userspace by a copyfollowed by a delete. Be aware that the original unencrypted datamay remain recoverable from free space on the disk; prefer to keepall files encrypted from the very beginning. Theshred programmay be used to overwrite the source files but isn’t guaranteed to beeffective on all filesystems and storage devices.
Direct I/O is supported on encrypted files only under somecircumstances. For details, seeDirect I/O support.
The fallocate operations FALLOC_FL_COLLAPSE_RANGE andFALLOC_FL_INSERT_RANGE are not supported on encrypted files and willfail with EOPNOTSUPP.
Online defragmentation of encrypted files is not supported. TheEXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail withEOPNOTSUPP.
The ext4 filesystem does not support data journaling with encryptedregular files. It will fall back to ordered data mode instead.
DAX (Direct Access) is not supported on encrypted files.
The maximum length of an encrypted symlink is 2 bytes shorter thanthe maximum length of an unencrypted symlink. For example, on anEXT4 filesystem with a 4K block size, unencrypted symlinks can be upto 4095 bytes long, while encrypted symlinks can only be up to 4093bytes long (both lengths excluding the terminating null).
Note that mmapis supported. This is possible because the pagecachefor an encrypted file contains the plaintext, not the ciphertext.
Without the key¶
Some filesystem operations may be performed on encrypted regularfiles, directories, and symlinks even before their encryption key hasbeen added, or after their encryption key has been removed:
File metadata may be read, e.g. using
stat()
.Directories may be listed, in which case the filenames will belisted in an encoded form derived from their ciphertext. Thecurrent encoding algorithm is described inFilename hashing andencoding. The algorithm is subject to change, but it isguaranteed that the presented filenames will be no longer thanNAME_MAX bytes, will not contain the
/
or\0
characters, andwill uniquely identify directory entries.The
.
and..
directory entries are special. They are alwayspresent and are not encrypted or encoded.Files may be deleted. That is, nondirectory files may be deletedwith
unlink()
as usual, and empty directories may be deleted withrmdir()
as usual. Therefore,rm
andrm-r
will work asexpected.Symlink targets may be read and followed, but they will be presentedin encrypted form, similar to filenames in directories. Hence, theyare unlikely to point to anywhere useful.
Without the key, regular files cannot be opened or truncated.Attempts to do so will fail with ENOKEY. This implies that anyregular file operations that require a file descriptor, such asread(), write(), mmap(),fallocate()
, and ioctl(), are also forbidden.
Also without the key, files of any type (including directories) cannotbe created or linked into an encrypted directory, nor can a name in anencrypted directory be the source or target of a rename, nor can anO_TMPFILE temporary file be created in an encrypted directory. Allsuch operations will fail with ENOKEY.
It is not currently possible to backup and restore encrypted fileswithout the encryption key. This would require special APIs whichhave not yet been implemented.
Encryption policy enforcement¶
After an encryption policy has been set on a directory, all regularfiles, directories, and symbolic links created in that directory(recursively) will inherit that encryption policy. Special files ---that is, named pipes, device nodes, and UNIX domain sockets --- willnot be encrypted.
Except for those special files, it is forbidden to have unencryptedfiles, or files encrypted with a different encryption policy, in anencrypted directory tree. Attempts to link or rename such a file intoan encrypted directory will fail with EXDEV. This is also enforcedduring ->lookup()
to provide limited protection against offlineattacks that try to disable or downgrade encryption in known locationswhere applications may later write sensitive data. It is recommendedthat systems implementing a form of “verified boot” take advantage ofthis by validating all top-level encryption policies prior to access.
Inline encryption support¶
Many newer systems (especially mobile SoCs) haveinline encryptionhardware that can encrypt/decrypt data while it is on its way to/fromthe storage device. Linux supports inline encryption through a set ofextensions to the block layer calledblk-crypto. blk-crypto allowsfilesystems to attach encryption contexts to bios (I/O requests) tospecify how the data will be encrypted or decrypted in-line. For moreinformation about blk-crypto, seeDocumentation/block/inline-encryption.rst.
On supported filesystems (currently ext4 and f2fs), fscrypt can useblk-crypto instead of the kernel crypto API to encrypt/decrypt filecontents. To enable this, set CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y inthe kernel configuration, and specify the “inlinecrypt” mount optionwhen mounting the filesystem.
Note that the “inlinecrypt” mount option just specifies to use inlineencryption when possible; it doesn’t force its use. fscrypt willstill fall back to using the kernel crypto API on files where theinline encryption hardware doesn’t have the needed crypto capabilities(e.g. support for the needed encryption algorithm and data unit size)and where blk-crypto-fallback is unusable. (For blk-crypto-fallbackto be usable, it must be enabled in the kernel configuration withCONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y, and the file must beprotected by a raw key rather than a hardware-wrapped key.)
Currently fscrypt always uses the filesystem block size (which isusually 4096 bytes) as the data unit size. Therefore, it can only useinline encryption hardware that supports that data unit size.
Inline encryption doesn’t affect the ciphertext or other aspects ofthe on-disk format, so users may freely switch back and forth betweenusing “inlinecrypt” and not using “inlinecrypt”. An exception is thatfiles that are protected by a hardware-wrapped key can only beencrypted/decrypted by the inline encryption hardware and thereforecan only be accessed when the “inlinecrypt” mount option is used. Formore information about hardware-wrapped keys, see below.
Hardware-wrapped keys¶
fscrypt supports usinghardware-wrapped keys when the inlineencryption hardware supports it. Such keys are only present in kernelmemory in wrapped (encrypted) form; they can only be unwrapped(decrypted) by the inline encryption hardware and are temporally boundto the current boot. This prevents the keys from being compromised ifkernel memory is leaked. This is done without limiting the number ofkeys that can be used and while still allowing the execution ofcryptographic tasks that are tied to the same key but can’t use inlineencryption hardware, e.g. filenames encryption.
Note that hardware-wrapped keys aren’t specific to fscrypt; they are ablock layer feature (part ofblk-crypto). For more details abouthardware-wrapped keys, see the block layer documentation atDocumentation/block/inline-encryption.rst. The rest of this section just focuses onthe details of how fscrypt can use hardware-wrapped keys.
fscrypt supports hardware-wrapped keys by allowing the fscrypt masterkeys to be hardware-wrapped keys as an alternative to raw keys. Toadd a hardware-wrapped key withFS_IOC_ADD_ENCRYPTION_KEY,userspace must specify FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED in theflags
field ofstructfscrypt_add_key_arg
and also in theflags
field ofstructfscrypt_provisioning_key_payload
whenapplicable. The key must be in ephemerally-wrapped form, notlong-term wrapped form.
Some limitations apply. First, files protected by a hardware-wrappedkey are tied to the system’s inline encryption hardware. Thereforethey can only be accessed when the “inlinecrypt” mount option is used,and they can’t be included in portable filesystem images. Second,currently the hardware-wrapped key support is only compatible withIV_INO_LBLK_64 policies andIV_INO_LBLK_32 policies, as itassumes that there is just one file contents encryption key perfscrypt master key rather than one per file. Future work may addressthis limitation by passing per-file nonces down the storage stack toallow the hardware to derive per-file keys.
Implementation-wise, to encrypt/decrypt the contents of files that areprotected by a hardware-wrapped key, fscrypt uses blk-crypto,attaching the hardware-wrapped key to the bio crypt contexts. As isthe case with raw keys, the block layer will program the key into akeyslot when it isn’t already in one. However, when programming ahardware-wrapped key, the hardware doesn’t program the given keydirectly into a keyslot but rather unwraps it (using the hardware’sephemeral wrapping key) and derives the inline encryption key from it.The inline encryption key is the key that actually gets programmedinto a keyslot, and it is never exposed to software.
However, fscrypt doesn’t just do file contents encryption; it alsouses its master keys to derive filenames encryption keys, keyidentifiers, and sometimes some more obscure types of subkeys such asdirhash keys. So even with file contents encryption out of thepicture, fscrypt still needs a raw key to work with. To get such akey from a hardware-wrapped key, fscrypt asks the inline encryptionhardware to derive a cryptographically isolated “software secret” fromthe hardware-wrapped key. fscrypt uses this “software secret” to keyits KDF to derive all subkeys other than file contents keys.
Note that this implies that the hardware-wrapped key feature onlyprotects the file contents encryption keys. It doesn’t protect otherfscrypt subkeys such as filenames encryption keys.
Direct I/O support¶
For direct I/O on an encrypted file to work, the following conditionsmust be met (in addition to the conditions for direct I/O on anunencrypted file):
The file must be using inline encryption. Usually this means thatthe filesystem must be mounted with
-oinlinecrypt
and inlineencryption hardware must be present. However, a software fallbackis also available. For details, seeInline encryption support.The I/O request must be fully aligned to the filesystem block size.This means that the file position the I/O is targeting, the lengthsof all I/O segments, and the memory addresses of all I/O buffersmust be multiples of this value. Note that the filesystem blocksize may be greater than the logical block size of the block device.
If either of the above conditions is not met, then direct I/O on theencrypted file will fall back to buffered I/O.
Implementation details¶
Encryption context¶
An encryption policy is represented on-disk bystructfscrypt_context_v1
orstructfscrypt_context_v2
. It is up toindividual filesystems to decide where to store it, but normally itwould be stored in a hidden extended attribute. It shouldnot beexposed by the xattr-related system calls such asgetxattr()
andsetxattr()
because of the special semantics of the encryption xattr.(In particular, there would be much confusion if an encryption policywere to be added to or removed from anything other than an emptydirectory.) These structs are defined as follows:
#define FSCRYPT_FILE_NONCE_SIZE 16#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8struct fscrypt_context_v1 { u8 version; u8 contents_encryption_mode; u8 filenames_encryption_mode; u8 flags; u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE]; u8 nonce[FSCRYPT_FILE_NONCE_SIZE];};#define FSCRYPT_KEY_IDENTIFIER_SIZE 16struct fscrypt_context_v2 { u8 version; u8 contents_encryption_mode; u8 filenames_encryption_mode; u8 flags; u8 log2_data_unit_size; u8 __reserved[3]; u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE]; u8 nonce[FSCRYPT_FILE_NONCE_SIZE];};
The context structs contain the same information as the correspondingpolicy structs (seeSetting an encryption policy), except that thecontext structs also contain a nonce. The nonce is randomly generatedby the kernel and is used as KDF input or as a tweak to causedifferent files to be encrypted differently; seePer-file encryptionkeys andDIRECT_KEY policies.
Data path changes¶
When inline encryption is used, filesystems just need to associateencryption contexts with bios to specify how the block layer or theinline encryption hardware will encrypt/decrypt the file contents.
When inline encryption isn’t used, filesystems must encrypt/decryptthe file contents themselves, as described below:
For the read path (->read_folio()
) of regular files, filesystems canread the ciphertext into the page cache and decrypt it in-place. Thefolio lock must be held until decryption has finished, to prevent thefolio from becoming visible to userspace prematurely.
For the write path (->writepages()
) of regular files, filesystemscannot encrypt data in-place in the page cache, since the cachedplaintext must be preserved. Instead, filesystems must encrypt into atemporary buffer or “bounce page”, then write out the temporarybuffer. Some filesystems, such as UBIFS, already use temporarybuffers regardless of encryption. Other filesystems, such as ext4 andF2FS, have to allocate bounce pages specially for encryption.
Filename hashing and encoding¶
Modern filesystems accelerate directory lookups by using indexeddirectories. An indexed directory is organized as a tree keyed byfilename hashes. When a ->lookup()
is requested, the filesystemnormally hashes the filename being looked up so that it can quicklyfind the corresponding directory entry, if any.
With encryption, lookups must be supported and efficient both with andwithout the encryption key. Clearly, it would not work to hash theplaintext filenames, since the plaintext filenames are unavailablewithout the key. (Hashing the plaintext filenames would also make itimpossible for the filesystem’s fsck tool to optimize encrypteddirectories.) Instead, filesystems hash the ciphertext filenames,i.e. the bytes actually stored on-disk in the directory entries. Whenasked to do a ->lookup()
with the key, the filesystem just encryptsthe user-supplied name to get the ciphertext.
Lookups without the key are more complicated. The raw ciphertext maycontain the\0
and/
characters, which are illegal infilenames. Therefore,readdir()
must base64url-encode the ciphertextfor presentation. For most filenames, this works fine; on ->lookup()
,the filesystem just base64url-decodes the user-supplied name to getback to the raw ciphertext.
However, for very long filenames, base64url encoding would cause thefilename length to exceed NAME_MAX. To prevent this,readdir()
actually presents long filenames in an abbreviated form which encodesa strong “hash” of the ciphertext filename, along with the optionalfilesystem-specific hash(es) needed for directory lookups. Thisallows the filesystem to still, with a high degree of confidence, mapthe filename given in ->lookup()
back to a particular directory entrythat was previously listed byreaddir()
. Seestructfscrypt_nokey_name
in the source for more details.
Note that the precise way that filenames are presented to userspacewithout the key is subject to change in the future. It is only meantas a way to temporarily present valid filenames so that commands likerm-r
work as expected on encrypted directories.
Tests¶
To test fscrypt, use xfstests, which is Linux’s de facto standardfilesystem test suite. First, run all the tests in the “encrypt”group on the relevant filesystem(s). One can also run the testswith the ‘inlinecrypt’ mount option to test the implementation forinline encryption support. For example, to test ext4 andf2fs encryption usingkvm-xfstests:
kvm-xfstests -c ext4,f2fs -g encryptkvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
UBIFS encryption can also be tested this way, but it should be done ina separate command, and it takes some time for kvm-xfstests to set upemulated UBI volumes:
kvm-xfstests -c ubifs -g encrypt
No tests should fail. However, tests that use non-default encryptionmodes (e.g. generic/549 and generic/550) will be skipped if the neededalgorithms were not built into the kernel’s crypto API. Also, teststhat access the raw block device (e.g. generic/399, generic/548,generic/549, generic/550) will be skipped on UBIFS.
Besides running the “encrypt” group tests, for ext4 and f2fs it’s alsopossible to run most xfstests with the “test_dummy_encryption” mountoption. This option causes all new files to be automaticallyencrypted with a dummy key, without having to make any API calls.This tests the encrypted I/O paths more thoroughly. To do this withkvm-xfstests, use the “encrypt” filesystem configuration:
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g autokvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
Because this runs many more tests than “-g encrypt” does, it takesmuch longer to run; so also consider usinggce-xfstestsinstead of kvm-xfstests:
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g autogce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt