요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
=====================================
Filesystem-level encryption (fscrypt)
=====================================
Introduction
============
fscrypt is a library which filesystems can hook into to support
transparent encryption of files and directories.
Note: "fscrypt" in this document refers to the kernel-level portion,
implemented in ``fs/crypto/``, as opposed to the userspace tool
`fscrypt <https://github.com/google/fscrypt>`_. This document only
covers the kernel-level portion. For command-line examples of how to
use encryption, see the documentation for the userspace tool `fscrypt
<https://github.com/google/fscrypt>`_. Also, it is recommended to use
the fscrypt userspace tool, or other existing userspace tools such as
`fscryptctl <https://github.com/google/fscryptctl>`_ or `Android's key
management system
<https://source.android.com/security/encryption/file-based>`_, over
using the kernel's API directly. Using existing tools reduces the
chance of introducing your own security bugs. (Nevertheless, for
completeness this documentation covers the kernel's API anyway.)
Unlike dm-crypt, fscrypt operates at the filesystem level rather than
at the block device level. This allows it to encrypt different files
with different keys and to have unencrypted files on the same
filesystem. This is useful for multi-user systems where each user's
data-at-rest needs to be cryptographically isolated from the others.
However, except for filenames, fscrypt does not encrypt filesystem
metadata.
Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated
directly into supported filesystems --- currently ext4, F2FS, UBIFS,
and CephFS. This allows encrypted files to be read and written
without caching both the decrypted and encrypted pages in the
pagecache, thereby nearly halving the memory used and bringing it in
line with unencrypted files. Similarly, half as many dentries and
inodes are needed. eCryptfs also limits encrypted filenames to 143
bytes, causing application compatibility issues; fscrypt allows the
full 255 bytes (NAME_MAX). Finally, unlike eCryptfs, the fscrypt API
can be used by unprivileged users, with no need to mount anything.
fscrypt does not support encrypting files in-place. Instead, it
supports marking an empty directory as encrypted. Then, after
userspace provides the key, all regular files, directories, and
symbolic links created in that directory tree are transparently
encrypted.
Threat model
============
Offline attacks
---------------
Provided that userspace chooses a strong encryption key, fscrypt
protects the confidentiality of file contents and filenames in the
event of a single point-in-time permanent offline compromise of the
block device content. fscrypt does not protect the confidentiality of
non-filename metadata, e.g. file sizes, file permissions, file
timestamps, and extended attributes. Also, the existence and location
of holes (unallocated blocks which logically contain all zeroes) in
files is not protected.
fscrypt is not guaranteed to protect confidentiality or authenticity
if an attacker is able to manipulate the filesystem offline prior to
an authorized user later accessing the filesystem.
Online attacks
--------------
fscrypt (and storage encryption in general) can only provide limited
protection against online attacks. In detail:
Side-channel attacks
~~~~~~~~~~~~~~~~~~~~
fscrypt is only resistant to side-channel attacks, such as timing or
electromagnetic attacks, to the extent that the underlying Linux
Cryptographic API algorithms or inline encryption hardware are. If a
vulnerable algorithm is used, such as a table-based implementation of
AES, it may be possible for an attacker to mount a side channel attack
against the online system. Side channel attacks may also be mounted
against applications consuming decrypted data.
Unauthorized file access
~~~~~~~~~~~~~~~~~~~~~~~~
After an encryption key has been added, fscrypt does not hide the
plaintext file contents or filenames from other users on the same
system. Instead, existing access control mechanisms such as file mode
bits, POSIX ACLs, LSMs, or namespaces should be used for this purpose.
(For the reasoning behind this, understand that while the key is
added, the confidentiality of the data, from the perspective of the
system itself, is *not* protected by the mathematical properties of
encryption but rather only by the correctness of the kernel.
Therefore, any encryption-specific access control checks would merely
be enforced by kernel *code* and therefore would be largely redundant
with the wide variety of access control mechanisms already available.)
Read-only kernel memory compromise
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unless `hardware-wrapped keys`_ are used, an attacker who gains the
ability to read from arbitrary kernel memory, e.g. by mounting a
physical attack or by exploiting a kernel security vulnerability, can
compromise all fscrypt keys that are currently in-use. This also
extends 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 master
keys and file contents encryption keys (but not other types of fscrypt
subkeys such as filenames encryption keys) are protected from
compromises of arbitrary kernel memory.
In addition, fscrypt allows encryption keys to be removed from the
kernel, which may protect them from later compromise.
In more detail, the FS_IOC_REMOVE_ENCRYPTION_KEY ioctl (or the
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS ioctl) can wipe a master
encryption key from kernel memory. If it does so, it will also try to
evict 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 will *not* be removed or wiped.
Therefore, for maximum effect, userspace should close the relevant
encrypted files and directories before removing a master key, as
well as kill any processes whose working directory is in an affected
encrypted directory.
- The kernel cannot magically wipe copies of the master key(s) that
userspace might have as well. Therefore, userspace must wipe all
copies of the master key(s) it makes as well; normally this should
be done immediately after FS_IOC_ADD_ENCRYPTION_KEY, without waiting
for FS_IOC_REMOVE_ENCRYPTION_KEY. Naturally, the same also applies
to all higher levels in the key hierarchy. Userspace should also
follow other security precautions such as mlock()ing memory
containing keys to prevent it from being swapped out.
- In general, decrypted contents and filenames in the kernel VFS
caches are freed but not wiped. Therefore, portions thereof may be
recoverable from freed memory, even after the corresponding key(s)
were wiped. To partially solve this, you can add init_on_free=1 to
your kernel command line. However, this has a performance cost.
- Secret keys might still exist in CPU registers or in other places
not explicitly considered here.
Full system compromise
~~~~~~~~~~~~~~~~~~~~~~
An attacker who gains "root" access and/or the ability to execute
arbitrary kernel code can freely exfiltrate data that is protected by
any in-use fscrypt keys. Thus, usually fscrypt provides no meaningful
protection in this scenario. (Data that is protected by a key that is
absent throughout the entire attack remains protected, modulo the
limitations of key removal mentioned above in the case where the key
was removed prior to the attack.)
However, if `hardware-wrapped keys`_ are used, such attackers will be
unable to exfiltrate the master keys or file contents keys in a form
that will be usable after the system is powered off. This may be
useful if the attacker is significantly time-limited and/or
bandwidth-limited, so they can only exfiltrate some data and need to
rely on a later offline attack to exfiltrate the rest of it.
Limitations of v1 policies
~~~~~~~~~~~~~~~~~~~~~~~~~~
v1 encryption policies have some weaknesses with respect to online
attacks:
- There is no verification that the provided master key is correct.
Therefore, a malicious user can temporarily associate the wrong key
with another user's encrypted files to which they have read-only
access. Because of filesystem caching, the wrong key will then be
used by the other user's accesses to those files, even if the other
user has the correct key in their own keyring. This violates the
meaning of "read-only access".
- A compromise of a per-file key also compromises the master key from
which it was derived.
- Non-root users cannot securely remove encryption keys.
All the above problems are fixed with v2 encryption policies. For
this reason among others, it is recommended to use v2 encryption
policies on all new encrypted directories.
Key hierarchy
=============
Note: this section assumes the use of raw keys rather than
hardware-wrapped keys. The use of hardware-wrapped keys modifies the
key hierarchy slightly. For details, see `Hardware-wrapped keys`_.
Master Keys
-----------
Each encrypted directory tree is protected by a *master key*. Master
keys can be up to 64 bytes long, and must be at least as long as the
greater of the security strength of the contents and filenames
encryption modes being used. For example, if any AES-256 mode is
used, the master key must be at least 256 bits, i.e. 32 bytes. A
stricter requirement applies if the key is used by a v1 encryption
policy and AES-256-XTS is used; such keys must be 64 bytes.
To "unlock" an encrypted directory tree, userspace must provide the
appropriate master key. There can be any number of master keys, each
of which protects any number of directory trees on any number of
filesystems.
Master keys must be real cryptographic keys, i.e. indistinguishable
from random bytestrings of the same length. This implies that users
**must not** directly use a password as a master key, zero-pad a
shorter key, or repeat a shorter key. Security cannot be guaranteed
if userspace makes any such error, as the cryptographic proofs and
analysis would no longer apply.
Instead, users should generate master keys either using a
cryptographically 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 such
as a passphrase, it is critical that a KDF designed for this purpose
be used, such as scrypt, PBKDF2, or Argon2.
Key derivation function
-----------------------
With one exception, fscrypt never uses the master key(s) for
encryption 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 whether
the key is used for v1 encryption policies or for v2 encryption
policies. Users **must not** use the same key for both v1 and v2
encryption policies. (No real-world attack is currently known on this
specific case of key reuse, but its security cannot be guaranteed
since the cryptographic proofs and analysis would no longer apply.)
For v1 encryption policies, the KDF only supports deriving per-file
encryption keys. It works by encrypting the master key with
AES-128-ECB, using the file's 16-byte nonce as the AES key. The
resulting ciphertext is used as the derived key. If the ciphertext is
longer than needed, then it is truncated to the needed length.
For v2 encryption policies, the KDF is HKDF-SHA512. The master key is
passed as the "input keying material", no salt is used, and a distinct
"application-specific information string" is used for each distinct
key to be derived. For example, when a per-file encryption key is
derived, the application-specific information string is the file's
nonce prefixed with "fscrypt\\0" and a context byte. Different
context bytes are used for other types of derived keys.
HKDF-SHA512 is preferred to the original AES-128-ECB based KDF because
HKDF is more flexible, is nonreversible, and evenly distributes
entropy from the master key. HKDF is also standardized and widely
used 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 two
files doesn't map to the same ciphertext, or vice versa. In most
cases, fscrypt does this by deriving per-file keys. When a new
encrypted inode (regular file, directory, or symlink) is created,
fscrypt randomly generates a 16-byte nonce and stores it in the
inode's encryption xattr. Then, it uses a KDF (as described in `Key
derivation function`_) to derive the file's key from the master key
and nonce.
Key derivation was chosen over key wrapping because wrapped keys would
require larger xattrs which would be less likely to fit in-line in the
filesystem's inode table, and there didn't appear to be any
significant advantages to key wrapping. In particular, currently
there is no requirement to support unlocking a file with multiple
alternative master keys or to support rotating master keys. Instead,
the master keys may be wrapped in userspace, e.g. as is done by the
`fscrypt <https://github.com/google/fscrypt>`_ tool.
DIRECT_KEY policies
-------------------
The Adiantum encryption mode (see `Encryption modes and usage`_) is
suitable for both contents and filenames encryption, and it accepts
long IVs --- long enough to hold both an 8-byte data unit index and a
16-byte per-file nonce. Also, the overhead of each Adiantum key is
greater 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 enabled
this 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 is
included in the IV. Moreover:
- For v1 encryption policies, the encryption is done directly with the
master key. Because of this, users **must not** use the same master
key for any other purpose, even for other v1 policies.
- For v2 encryption policies, the encryption is done with a per-mode
key derived using the KDF. Users may use the same master key for
other 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 mode
number, and filesystem UUID. This normally results in all files
protected by the same master key sharing a single contents encryption
key and a single filenames encryption key. To still encrypt different
files' 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 hardware
compliant with the UFS standard, which supports only 64 IV bits per
I/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 for
IV_INO_LBLK_32, the inode number is hashed with SipHash-2-4 (where the
SipHash key is derived from the master key) and added to the file data
unit index mod 2^32 to produce a 32-bit IV.
This format is optimized for use with inline encryption hardware
compliant with the eMMC v5.2 standard, which supports only 32 IV bits
per I/O request and may have only a small number of keyslots. This
format results in some level of IV reuse, so it should only be used
when necessary due to hardware limitations.
Key identifiers
---------------
For master keys used for v2 encryption policies, a unique 16-byte "key
identifier" is also derived using the KDF. This value is stored in
the clear, since it is needed to reliably identify the key itself.
Dirhash keys
------------
For directories that are indexed using a secret-keyed dirhash over the
plaintext filenames, the KDF is also used to derive a 128-bit
SipHash-2-4 key per directory in order to hash filenames. This works
just like deriving a per-file encryption key, except that a different
KDF 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 contents
and one encryption mode to be specified for filenames. Different
directory 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 of
the difficulty of dealing with ciphertext expansion. Therefore,
contents encryption uses a block cipher in `XTS mode
<https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS>`_ or
`CBC-ESSIV mode
<https://en.wikipedia.org/wiki/Disk_encryption_theory#Encrypted_salt-sector_initialization_vector_(ESSIV)>`_,
or a wide-block cipher. Filenames encryption uses a
block cipher in `CBC-CTS mode
<https://en.wikipedia.org/wiki/Ciphertext_stealing>`_ or a wide-block
cipher.
The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default.
It is also the only option that is *guaranteed* to always be supported
if the kernel supports fscrypt at all; see `Kernel config options`_.
The (AES-256-XTS, AES-256-HCTR2) pair is also a good choice that
upgrades the filenames encryption to use a wide-block cipher. (A
*wide-block cipher*, also called a tweakable super-pseudorandom
permutation, has the property that changing one bit scrambles the
entire result.) As described in `Filenames encryption`_, a wide-block
cipher is the ideal mode for the problem domain, though CBC-CTS is the
"least bad" choice among the alternatives. For more information about
HCTR2, see `the HCTR2 paper <https://eprint.iacr.org/2021/1441.pdf>`_.
Adiantum is recommended on systems where AES is too slow due to lack
of hardware acceleration for AES. Adiantum is a wide-block cipher
that uses XChaCha12 and AES-256 as its underlying components. Most of
the work is done by XChaCha12, which is much faster than AES when AES
acceleration is unavailable. For more information about Adiantum, see
`the Adiantum paper <https://eprint.iacr.org/2018/720.pdf>`_.
The (AES-128-CBC-ESSIV, AES-128-CBC-CTS) pair was added to try to
provide a more efficient option for systems that lack AES instructions
in the CPU but do have a non-inline crypto engine such as CAAM or CESA
that supports AES-CBC (and not AES-XTS). This is deprecated. It has
been 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 they
receive limited security review compared to the usual choices such as
AES and ChaCha. They also don't bring much new to the table. It is
suggested to only use these ciphers where their use is mandated.
Kernel config options
---------------------
Enabling fscrypt support (CONFIG_FS_ENCRYPTION) automatically pulls in
only the basic support from the crypto API needed to use AES-256-XTS
and AES-256-CBC-CTS encryption. For optimal performance, it is
strongly recommended to also enable any available platform-specific
kconfig options that provide acceleration for the algorithm(s) you
wish to use. Support for any "non-default" encryption modes typically
requires extra kconfig options as well.
Below, some relevant options are listed by encryption mode. Note,
acceleration options not listed below may be available for your
platform; refer to the kconfig menus. File contents encryption can
also be configured to use inline encryption hardware instead of the
kernel crypto API (see `Inline encryption support`_); in that case,
the file contents mode doesn't need to supported in the kernel crypto
API, 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 "data
units". Each data unit is encrypted independently. The IV for each
data unit incorporates the zero-based index of the data unit within
the file. This ensures that each data unit within a file is encrypted
differently, which is essential to prevent leaking information.
Note: the encryption depending on the offset into the file means that
operations like "collapse range" and "insert range" that rearrange the
extent 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 UBIFS
work. A file's data units are all the same size; the last data unit
is zero-padded if needed. By default, the data unit size is equal
to the filesystem block size. On some filesystems, users can select
a sub-block data unit size via the ``log2_data_unit_size`` field of
the encryption policy; see `FS_IOC_SET_ENCRYPTION_POLICY`_.
* Variable-size data units. This is what UBIFS does. Each "UBIFS
data node" is treated as a crypto data unit. Each contains variable
length, possibly compressed data, zero-padded to the next 16-byte
boundary. Users cannot select a sub-block data unit size on UBIFS.
In the case of compression + encryption, the compressed data is
encrypted. UBIFS compression works as described above. f2fs
compression works a bit differently; it compresses a number of
filesystem blocks into a smaller number of filesystem blocks.
Therefore a f2fs-compressed file still uses fixed-size data units, and
it is encrypted in a similar way to a file containing holes.
As mentioned in `Key hierarchy`_, the default encryption setting uses
per-file keys. In this case, the IV for each data unit is simply the
index of the data unit in the file. However, users can select an
encryption setting that does not use per-file keys. For these, some
kind of file identifier is incorporated into the IVs as follows:
- With `DIRECT_KEY policies`_, the data unit index is placed in bits
0-63 of the IV, and the file's nonce is placed in bits 64-191.
- With `IV_INO_LBLK_64 policies`_, the data unit index is placed in
bits 0-31 of the IV, and the file's inode number is placed in bits
32-63. This setting is only allowed when data unit indices and
inode numbers fit in 32 bits.
- With `IV_INO_LBLK_32 policies`_, the file's inode number is hashed
and added to the data unit index. The resulting value is truncated
to 32 bits and placed in bits 0-31 of the IV. This setting is only
allowed 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, an
ESSIV layer is automatically included. In this case, before the IV is
passed to AES-128-CBC, it is encrypted with AES-256 where the AES-256
key is the SHA-256 hash of the file's contents encryption key.
Filenames encryption
--------------------
For filenames, each full filename is encrypted at once. Because of
the requirements to retain support for efficient directory lookups and
filenames of up to 255 bytes, the same IV is used for every filename
in a directory.
However, each encrypted directory still uses a unique key, or
alternatively has the file's nonce (for `DIRECT_KEY policies`_) or
inode number (for `IV_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 a
common prefix at least as long as the cipher block size (16 bytes for AES), the
corresponding encrypted filenames will also share a common prefix. This is
undesirable. Adiantum and HCTR2 do not have this weakness, as they are
wide-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 before
being encrypted. In addition, to reduce leakage of filename lengths
via their ciphertexts, all filenames are NUL-padded to the next 4, 8,
16, or 32-byte boundary (configurable). 32 is recommended since this
provides the best confidentiality, at the cost of making directory
entries consume slightly more space. Note that since NUL (``\0``) is
not otherwise a valid character in filenames, the padding will never
produce duplicate plaintexts.
Symbolic link targets are considered a type of filename and are
encrypted in the same way as filenames in directory entries, except
that 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 an
empty directory or verifies that a directory or regular file already
has the specified encryption policy. It takes in a pointer to
struct fscrypt_policy_v1 or struct fscrypt_policy_v2, defined as
follows::
#define FSCRYPT_POLICY_V1 0
#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8
struct 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 16
struct 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) if
struct fscrypt_policy_v1 is used or FSCRYPT_POLICY_V2 (2) if
struct fscrypt_policy_v2 is used. (Note: we refer to the original
policy version as "v1", though its version code is really 0.)
For new encrypted directories, use v2 policies.
- ``contents_encryption_mode`` and ``filenames_encryption_mode`` must
be set to constants from ``<linux/fscrypt.h>`` which identify the
encryption modes to use. If unsure, use FSCRYPT_MODE_AES_256_XTS
(1) for ``contents_encryption_mode`` and FSCRYPT_MODE_AES_256_CTS
(4) for ``filenames_encryption_mode``. For details, see `Encryption
modes 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 support
all combinations documented in `Supported modes`_.
- ``flags`` contains optional flags from ``<linux/fscrypt.h>``:
- FSCRYPT_POLICY_FLAGS_PAD_*: The amount of NUL padding to use when
encrypting filenames. If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32
(0x3).
- FSCRYPT_POLICY_FLAG_DIRECT_KEY: See `DIRECT_KEY policies`_.
- FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: See `IV_INO_LBLK_64
policies`_.
- FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: See `IV_INO_LBLK_32
policies`_.
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 are
mutually 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 is
the granularity of file contents encryption. For example, setting
``log2_data_unit_size`` to 12 causes file contents be passed to the
underlying encryption algorithm (such as AES-256-XTS) in 4096-byte
data units, each with its own IV.
Not all filesystems support setting ``log2_data_unit_size``. ext4
and f2fs support it since Linux v6.7. On filesystems that support
it, the supported nonzero values are 9 through the log2 of the
filesystem block size, inclusively. The default value of 0 selects
the filesystem block size.
The main use case for ``log2_data_unit_size`` is for selecting a
data unit size smaller than the filesystem block size for
compatibility with inline encryption hardware that only supports
smaller data unit sizes. ``/sys/block/$disk/queue/crypto/`` may be
useful for checking which data unit sizes are supported by a
particular system's inline encryption hardware.
Leave this field zeroed unless you are certain you need it. Using
an unnecessarily small data unit size reduces performance.
- For v2 encryption policies, ``__reserved`` must be zeroed.
- For v1 encryption policies, ``master_key_descriptor`` specifies how
to find the master key in a keyring; see `Adding keys`_. It is up
to userspace to choose a unique ``master_key_descriptor`` for each
master key. The e4crypt and fscrypt tools use the first 8 bytes of
``SHA-512(SHA-512(master_key))``, but this particular scheme is not
required. Also, the master key need not be in the keyring yet when
FS_IOC_SET_ENCRYPTION_POLICY is executed. However, it must be added
before any files can be created in the encrypted directory.
For v2 encryption policies, ``master_key_descriptor`` has been
replaced with ``master_key_identifier``, which is longer and cannot
be arbitrarily chosen. Instead, the key must first be added using
`FS_IOC_ADD_ENCRYPTION_KEY`_. Then, the ``key_spec.u.identifier``
the kernel returned in the struct fscrypt_add_key_arg must
be used as the ``master_key_identifier`` in
struct fscrypt_policy_v2.
If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY
verifies that the file is an empty directory. If so, the specified
encryption policy is assigned to the directory, turning it into an
encrypted directory. After that, and after providing the
corresponding master key as described in `Adding keys`_, all regular
files, directories (recursively), and symlinks created in the
directory 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, then
FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption
policy exactly matches the actual one. If they match, then the ioctl
returns 0. Otherwise, it fails with EEXIST. This works on both
regular files and directories, including nonempty directories.
When a v2 encryption policy is assigned to a directory, it is also
required that either the specified key has been added by the current
user or that the caller has CAP_FOWNER in the initial user namespace.
(This is needed to prevent a user from encrypting their data with
another user's key.) The key must remain added while
FS_IOC_SET_ENCRYPTION_POLICY is executing. However, if the new
encrypted directory does not need to be accessed immediately, then the
key can be removed right away afterwards.
Note that the ext4 filesystem does not allow the root directory to be
encrypted, even if it is empty. Users who want to encrypt an entire
filesystem 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 the
process have the CAP_FOWNER capability in a namespace with the file
owner's uid mapped
- ``EEXIST``: the file is already encrypted with an encryption policy
different from the one specified
- ``EINVAL``: an invalid encryption policy was specified (invalid
version, mode(s), or flags; or reserved bits were set); or a v1
encryption policy was specified but the directory has the casefold
flag enabled (casefolding is incompatible with v1 policies).
- ``ENOKEY``: a v2 encryption policy was specified, but the key with
the specified ``master_key_identifier`` has not been added, nor does
the process have the CAP_FOWNER capability in the initial user
namespace
- ``ENOTDIR``: the file is unencrypted and is a regular file, not a
directory
- ``ENOTEMPTY``: the file is unencrypted and is a nonempty directory
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for filesystems, or the filesystem superblock has not
had encryption enabled on it. (For example, to use encryption on an
ext4 filesystem, CONFIG_FS_ENCRYPTION must be enabled in the
kernel config, and the superblock must have had the "encrypt"
feature flag enabled using ``tune2fs -O encrypt`` or ``mkfs.ext4 -O
encrypt``.)
- ``EPERM``: this directory may not be encrypted, e.g. because it is
the root directory of an ext4 filesystem
- ``EROFS``: the filesystem is readonly
Getting an encryption policy
----------------------------
Two ioctls are available to get a file's encryption policy:
- `FS_IOC_GET_ENCRYPTION_POLICY_EX`_
- `FS_IOC_GET_ENCRYPTION_POLICY`_
The extended (_EX) version of the ioctl is more general and is
recommended to use when possible. However, on older kernels only the
original ioctl is available. Applications should try the extended
version, and if it fails with ENOTTY fall back to the original
version.
FS_IOC_GET_ENCRYPTION_POLICY_EX
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_GET_ENCRYPTION_POLICY_EX ioctl retrieves the encryption
policy, if any, for a directory or regular file. No additional
permissions are required beyond the ability to open the file. It
takes in a pointer to struct fscrypt_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 initialize ``policy_size`` to the size available for
the policy struct, i.e. ``sizeof(arg.policy)``.
On success, the policy struct is returned in ``policy``, and its
actual size is returned in ``policy_size``. ``policy.version`` should
be checked to determine the version of policy returned. Note that the
version 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 unrecognized
encryption policy version
- ``ENODATA``: the file is not encrypted
- ``ENOTTY``: 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 encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it
- ``EOVERFLOW``: the file is encrypted and uses a recognized
encryption policy version, but the policy struct does not fit into
the provided buffer
Note: if you only need to know whether a file is encrypted or not, on
most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl
and check for FS_ENCRYPT_FL, or to use the statx() system call and
check for STATX_ATTR_ENCRYPTED in stx_attributes.
FS_IOC_GET_ENCRYPTION_POLICY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve the
encryption policy, if any, for a directory or regular file. However,
unlike `FS_IOC_GET_ENCRYPTION_POLICY_EX`_,
FS_IOC_GET_ENCRYPTION_POLICY only supports the original policy
version. It takes in a pointer directly to struct fscrypt_policy_v1
rather than struct fscrypt_get_policy_ex_arg.
The error codes for FS_IOC_GET_ENCRYPTION_POLICY are the same as those
for FS_IOC_GET_ENCRYPTION_POLICY_EX, except that
FS_IOC_GET_ENCRYPTION_POLICY also returns ``EINVAL`` if the file is
encrypted using a newer encryption policy version.
Getting the per-filesystem salt
-------------------------------
Some filesystems, such as ext4 and F2FS, also support the deprecated
ioctl FS_IOC_GET_ENCRYPTION_PWSALT. This ioctl retrieves a randomly
generated 16-byte value stored in the filesystem superblock. This
value is intended to used as a salt when deriving an encryption key
from a passphrase or other low-entropy user credential.
FS_IOC_GET_ENCRYPTION_PWSALT is deprecated. Instead, prefer to
generate 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 the
encryption is being done correctly. It is not needed for normal use
of fscrypt.
Adding keys
-----------
FS_IOC_ADD_ENCRYPTION_KEY
~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_ADD_ENCRYPTION_KEY ioctl adds a master encryption key to
the filesystem, making all files on the filesystem which were
encrypted 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 in
a pointer to struct fscrypt_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 2
struct 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[];
};
struct fscrypt_add_key_arg must be zeroed, then initialized
as follows:
- If the key is being added for use by v1 encryption policies, then
``key_spec.type`` must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, and
``key_spec.u.descriptor`` must contain the descriptor of the key
being added, corresponding to the value in the
``master_key_descriptor`` field of struct fscrypt_policy_v1.
To add this type of key, the calling process must have the
CAP_SYS_ADMIN capability in the initial user namespace.
Alternatively, if the key is being added for use by v2 encryption
policies, then ``key_spec.type`` must contain
FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, and ``key_spec.u.identifier`` is
an *output* field which the kernel fills in with a cryptographic
hash of the key. To add this type of key, the calling process does
not need any privileges. However, the number of keys that can be
added is limited by the user's quota for the keyrings service (see
``Documentation/security/keys/core.rst``).
- ``raw_size`` must be the size of the ``raw`` key provided, in bytes.
Alternatively, if ``key_id`` is nonzero, this field must be 0, since
in that case the size is implied by the specified Linux keyring key.
- ``key_id`` is 0 if the key is given directly in the ``raw`` field.
Otherwise ``key_id`` is the ID of a Linux keyring key of type
"fscrypt-provisioning" whose payload is struct
fscrypt_provisioning_key_payload whose ``raw`` field contains the
key, whose ``type`` field matches ``key_spec.type``, and whose
``flags`` field matches ``flags``. Since ``raw`` is
variable-length, the total size of this key's payload must be
``sizeof(struct fscrypt_provisioning_key_payload)`` plus the number
of key bytes. The process must have Search permission on this key.
Most users should leave this 0 and specify the key directly. The
support for specifying a Linux keyring key is intended mainly to
allow 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 a
hardware-wrapped key. See `Hardware-wrapped keys`_. This flag
can't be used if FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR is used.
- ``raw`` is a variable-length field which must contain the actual
key, ``raw_size`` bytes long. Alternatively, if ``key_id`` is
nonzero, then this field is unused. Note that despite being named
``raw``, if FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED is specified then it
will contain a wrapped key, not a raw key.
For v2 policy keys, the kernel keeps track of which user (identified
by effective user ID) added the key, and only allows the key to be
removed by that user --- or by "root", if they use
`FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_.
However, if another user has added the key, it may be desirable to
prevent that other user from unexpectedly removing it. Therefore,
FS_IOC_ADD_ENCRYPTION_KEY may also be used to add a v2 policy key
*again*, 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 the
current user, rather than actually add the key again (but the key must
still be provided, as a proof of knowledge).
FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim to
the 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 the
caller does not have the CAP_SYS_ADMIN capability in the initial
user namespace; or the key was specified by Linux key ID but the
process lacks Search permission on the key.
- ``EBADMSG``: invalid hardware-wrapped key
- ``EDQUOT``: the key quota for this user would be exceeded by adding
the key
- ``EINVAL``: invalid key size or key specifier type, or reserved bits
were set
- ``EKEYREJECTED``: the key was specified by Linux key ID, but the key
has the wrong type
- ``ENOKEY``: the key was specified by Linux key ID, but no key exists
with that ID
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it; or a hardware wrapped key was specified
but the filesystem does not support inline encryption or the hardware
does not support hardware-wrapped keys
Legacy method
~~~~~~~~~~~~~
For v1 encryption policies, a master encryption key can also be
provided by adding it to a process-subscribed keyring, e.g. to a
session keyring, or to a user keyring if the user keyring is linked
into the session keyring.
This method is deprecated (and not supported for v2 encryption
policies) for several reasons. First, it cannot be used in
combination with FS_IOC_REMOVE_ENCRYPTION_KEY (see `Removing keys`_),
so for removing a key a workaround such as keyctl_unlink() in
combination with ``sync; echo 2 > /proc/sys/vm/drop_caches`` would
have to be used. Second, it doesn't match the fact that the
locked/unlocked status of encrypted files (i.e. whether they appear to
be in plaintext form or in ciphertext form) is global. This mismatch
has caused much confusion as well as real problems when processes
running under different UIDs, such as a ``sudo`` command, need to
access encrypted files.
Nevertheless, to add a key to one of the process-subscribed keyrings,
the add_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 be
read back by userspace. The key description must be "fscrypt:"
followed by the 16-character lower case hex representation of the
``master_key_descriptor`` that was set in the encryption policy. The
key payload must conform to the following structure::
#define FSCRYPT_MAX_KEY_SIZE 64
struct 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 in
``raw`` with ``size`` indicating its size in bytes. That is, the
bytes ``raw[0..size-1]`` (inclusive) are the actual key.
The key description prefix "fscrypt:" may alternatively be replaced
with a filesystem-specific prefix such as "ext4:". However, the
filesystem-specific prefixes are deprecated and should not be used in
new programs.
Removing keys
-------------
Two ioctls are available for removing a key that was added by
`FS_IOC_ADD_ENCRYPTION_KEY`_:
- `FS_IOC_REMOVE_ENCRYPTION_KEY`_
- `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_
These two ioctls differ only in cases where v2 policy keys are added
or removed by non-root users.
These ioctls don't work on keys that were added via the legacy
process-subscribed keyrings mechanism.
Before using these ioctls, read the `Online attacks`_ section for a
discussion 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 master
encryption key from the filesystem, and possibly removes the key
itself. It can be executed on any file or directory on the target
filesystem, but using the filesystem's root directory is recommended.
It takes in a pointer to struct fscrypt_remove_key_arg, defined
as 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 fill
in ``key_spec.u.descriptor``. To remove this type of key, the
calling process must have the CAP_SYS_ADMIN capability in the
initial user namespace.
- To remove a key used by v2 encryption policies, set
``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
in ``key_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's
claim 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, and
FS_IOC_REMOVE_ENCRYPTION_KEY will only succeed as uid 1000. Or, if
both uids 1000 and 2000 added the key, then for each uid
FS_IOC_REMOVE_ENCRYPTION_KEY will only remove their own claim. Only
once *both* are removed is the key really removed. (Think of it like
unlinking a file that may have hard links.)
If FS_IOC_REMOVE_ENCRYPTION_KEY really removes the key, it will also
try to "lock" all files that had been unlocked with the key. It won't
lock files that are still in-use, so this ioctl is expected to be used
in cooperation with userspace ensuring that none of the files are
still open. However, if necessary, this ioctl can be executed again
later 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 to
the key was removed, or the key was already removed but had files
remaining to be the locked so the ioctl retried locking them. In any
of these cases, ``removal_status_flags`` is filled in with the
following 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 only
the user's claim to the key was removed.
- ``FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS``: set if only the
user'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 type
was specified, but the caller does not have the CAP_SYS_ADMIN
capability in the initial user namespace
- ``EINVAL``: invalid key specifier type, or reserved bits were set
- ``ENOKEY``: the key object was not found at all, i.e. it was never
added in the first place or was already fully removed including all
files locked; or, the user does not have a claim to the key (but
someone else does).
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same as
`FS_IOC_REMOVE_ENCRYPTION_KEY`_, except that for v2 policy keys, the
ALL_USERS version of the ioctl will remove all users' claims to the
key, not just the current user's. I.e., the key itself will always be
removed, no matter how many users have added it. This difference is
only 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 user
namespace. 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 a
master encryption key. It can be executed on any file or directory on
the target filesystem, but using the filesystem's root directory is
recommended. It takes in a pointer to
struct fscrypt_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 in ``key_spec``:
- To get the status of a key for v1 encryption policies, set
``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
in ``key_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 fill
in ``key_spec.u.identifier``.
On success, 0 is returned and the kernel fills in the output fields:
- ``status`` indicates whether the key is absent, present, or
incompletely removed. Incompletely removed means that removal has
been initiated, but some files are still in use; i.e.,
`FS_IOC_REMOVE_ENCRYPTION_KEY`_ returned 0 but set the informational
status 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 key
has added by the current user. This is only set for keys
identified by ``identifier`` rather than by ``descriptor``.
- ``user_count`` specifies the number of users who have added the key.
This is only set for keys identified by ``identifier`` rather than
by ``descriptor``.
FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:
- ``EINVAL``: invalid key specifier type, or reserved bits were set
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it
Among other use cases, FS_IOC_GET_ENCRYPTION_KEY_STATUS can be useful
for determining whether the key for a given encrypted directory needs
to be added before prompting the user for the passphrase needed to
derive the key.
FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys in
the filesystem-level keyring, i.e. the keyring managed by
`FS_IOC_ADD_ENCRYPTION_KEY`_ and `FS_IOC_REMOVE_ENCRYPTION_KEY`_. It
cannot get the status of a key that has only been added for use by v1
encryption policies using the legacy mechanism involving
process-subscribed keyrings.
Access semantics
================
With the key
------------
With the encryption key, encrypted regular files, directories, and
symlinks 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 encryption
policy (i.e. different key, modes, or flags), cannot be renamed or
linked into an encrypted directory; see `Encryption policy
enforcement`_. Attempts to do so will fail with EXDEV. However,
encrypted files can be renamed within an encrypted directory, or
into an unencrypted directory.
Note: "moving" an unencrypted file into an encrypted directory, e.g.
with the `mv` program, is implemented in userspace by a copy
followed by a delete. Be aware that the original unencrypted data
may remain recoverable from free space on the disk; prefer to keep
all files encrypted from the very beginning. The `shred` program
may be used to overwrite the source files but isn't guaranteed to be
effective on all filesystems and storage devices.
- Direct I/O is supported on encrypted files only under some
circumstances. For details, see `Direct I/O support`_.
- The fallocate operations FALLOC_FL_COLLAPSE_RANGE and
FALLOC_FL_INSERT_RANGE are not supported on encrypted files and will
fail with EOPNOTSUPP.
- Online defragmentation of encrypted files is not supported. The
EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
EOPNOTSUPP.
- The ext4 filesystem does not support data journaling with encrypted
regular 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 than
the maximum length of an unencrypted symlink. For example, on an
EXT4 filesystem with a 4K block size, unencrypted symlinks can be up
to 4095 bytes long, while encrypted symlinks can only be up to 4093
bytes long (both lengths excluding the terminating null).
Note that mmap *is* supported. This is possible because the pagecache
for an encrypted file contains the plaintext, not the ciphertext.
Without the key
---------------
Some filesystem operations may be performed on encrypted regular
files, directories, and symlinks even before their encryption key has
been 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 be
listed in an encoded form derived from their ciphertext. The
current encoding algorithm is described in `Filename hashing and
encoding`_. The algorithm is subject to change, but it is
guaranteed that the presented filenames will be no longer than
NAME_MAX bytes, will not contain the ``/`` or ``\0`` characters, and
will uniquely identify directory entries.
The ``.`` and ``..`` directory entries are special. They are always
present and are not encrypted or encoded.
- Files may be deleted. That is, nondirectory files may be deleted
with unlink() as usual, and empty directories may be deleted with
rmdir() as usual. Therefore, ``rm`` and ``rm -r`` will work as
expected.
- Symlink targets may be read and followed, but they will be presented
in encrypted form, similar to filenames in directories. Hence, they
are 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 any
regular file operations that require a file descriptor, such as
read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.
Also without the key, files of any type (including directories) cannot
be created or linked into an encrypted directory, nor can a name in an
encrypted directory be the source or target of a rename, nor can an
O_TMPFILE temporary file be created in an encrypted directory. All
such operations will fail with ENOKEY.
It is not currently possible to backup and restore encrypted files
without the encryption key. This would require special APIs which
have not yet been implemented.
Encryption policy enforcement
=============================
After an encryption policy has been set on a directory, all regular
files, 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 --- will
not be encrypted.
Except for those special files, it is forbidden to have unencrypted
files, or files encrypted with a different encryption policy, in an
encrypted directory tree. Attempts to link or rename such a file into
an encrypted directory will fail with EXDEV. This is also enforced
during ->lookup() to provide limited protection against offline
attacks that try to disable or downgrade encryption in known locations
where applications may later write sensitive data. It is recommended
that systems implementing a form of "verified boot" take advantage of
this by validating all top-level encryption policies prior to access.
Inline encryption support
=========================
Many newer systems (especially mobile SoCs) have *inline encryption
hardware* that can encrypt/decrypt data while it is on its way to/from
the storage device. Linux supports inline encryption through a set of
extensions to the block layer called *blk-crypto*. blk-crypto allows
filesystems to attach encryption contexts to bios (I/O requests) to
specify how the data will be encrypted or decrypted in-line. For more
information about blk-crypto, see
:ref:`Documentation/block/inline-encryption.rst <inline_encryption>`.
On supported filesystems (currently ext4 and f2fs), fscrypt can use
blk-crypto instead of the kernel crypto API to encrypt/decrypt file
contents. To enable this, set CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y in
the kernel configuration, and specify the "inlinecrypt" mount option
when mounting the filesystem.
Note that the "inlinecrypt" mount option just specifies to use inline
encryption when possible; it doesn't force its use. fscrypt will
still fall back to using the kernel crypto API on files where the
inline 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-fallback
to be usable, it must be enabled in the kernel configuration with
CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y, and the file must be
protected by a raw key rather than a hardware-wrapped key.)
Currently fscrypt always uses the filesystem block size (which is
usually 4096 bytes) as the data unit size. Therefore, it can only use
inline encryption hardware that supports that data unit size.
Inline encryption doesn't affect the ciphertext or other aspects of
the on-disk format, so users may freely switch back and forth between
using "inlinecrypt" and not using "inlinecrypt". An exception is that
files that are protected by a hardware-wrapped key can only be
encrypted/decrypted by the inline encryption hardware and therefore
can only be accessed when the "inlinecrypt" mount option is used. For
more information about hardware-wrapped keys, see below.
Hardware-wrapped keys
---------------------
fscrypt supports using *hardware-wrapped keys* when the inline
encryption hardware supports it. Such keys are only present in kernel
memory in wrapped (encrypted) form; they can only be unwrapped
(decrypted) by the inline encryption hardware and are temporally bound
to the current boot. This prevents the keys from being compromised if
kernel memory is leaked. This is done without limiting the number of
keys that can be used and while still allowing the execution of
cryptographic tasks that are tied to the same key but can't use inline
encryption hardware, e.g. filenames encryption.
Note that hardware-wrapped keys aren't specific to fscrypt; they are a
block layer feature (part of *blk-crypto*). For more details about
hardware-wrapped keys, see the block layer documentation at
:ref:`Documentation/block/inline-encryption.rst
<hardware_wrapped_keys>`. The rest of this section just focuses on
the details of how fscrypt can use hardware-wrapped keys.
fscrypt supports hardware-wrapped keys by allowing the fscrypt master
keys to be hardware-wrapped keys as an alternative to raw keys. To
add a hardware-wrapped key with `FS_IOC_ADD_ENCRYPTION_KEY`_,
userspace must specify FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED in the
``flags`` field of struct fscrypt_add_key_arg and also in the
``flags`` field of struct fscrypt_provisioning_key_payload when
applicable. The key must be in ephemerally-wrapped form, not
long-term wrapped form.
Some limitations apply. First, files protected by a hardware-wrapped
key are tied to the system's inline encryption hardware. Therefore
they 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 with
`IV_INO_LBLK_64 policies`_ and `IV_INO_LBLK_32 policies`_, as it
assumes that there is just one file contents encryption key per
fscrypt master key rather than one per file. Future work may address
this limitation by passing per-file nonces down the storage stack to
allow the hardware to derive per-file keys.
Implementation-wise, to encrypt/decrypt the contents of files that are
protected by a hardware-wrapped key, fscrypt uses blk-crypto,
attaching the hardware-wrapped key to the bio crypt contexts. As is
the case with raw keys, the block layer will program the key into a
keyslot when it isn't already in one. However, when programming a
hardware-wrapped key, the hardware doesn't program the given key
directly into a keyslot but rather unwraps it (using the hardware's
ephemeral wrapping key) and derives the inline encryption key from it.
The inline encryption key is the key that actually gets programmed
into a keyslot, and it is never exposed to software.
However, fscrypt doesn't just do file contents encryption; it also
uses its master keys to derive filenames encryption keys, key
identifiers, and sometimes some more obscure types of subkeys such as
dirhash keys. So even with file contents encryption out of the
picture, fscrypt still needs a raw key to work with. To get such a
key from a hardware-wrapped key, fscrypt asks the inline encryption
hardware to derive a cryptographically isolated "software secret" from
the hardware-wrapped key. fscrypt uses this "software secret" to key
its KDF to derive all subkeys other than file contents keys.
Note that this implies that the hardware-wrapped key feature only
protects the file contents encryption keys. It doesn't protect other
fscrypt subkeys such as filenames encryption keys.
Direct I/O support
==================
For direct I/O on an encrypted file to work, the following conditions
must be met (in addition to the conditions for direct I/O on an
unencrypted file):
* The file must be using inline encryption. Usually this means that
the filesystem must be mounted with ``-o inlinecrypt`` and inline
encryption hardware must be present. However, a software fallback
is also available. For details, see `Inline 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 lengths
of all I/O segments, and the memory addresses of all I/O buffers
must be multiples of this value. Note that the filesystem block
size 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 the
encrypted file will fall back to buffered I/O.
Implementation details
======================
Encryption context
------------------
An encryption policy is represented on-disk by
struct fscrypt_context_v1 or struct fscrypt_context_v2. It is up to
individual filesystems to decide where to store it, but normally it
would be stored in a hidden extended attribute. It should *not* be
exposed by the xattr-related system calls such as getxattr() and
setxattr() because of the special semantics of the encryption xattr.
(In particular, there would be much confusion if an encryption policy
were to be added to or removed from anything other than an empty
directory.) These structs are defined as follows::
#define FSCRYPT_FILE_NONCE_SIZE 16
#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8
struct 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 16
struct 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 corresponding
policy structs (see `Setting an encryption policy`_), except that the
context structs also contain a nonce. The nonce is randomly generated
by the kernel and is used as KDF input or as a tweak to cause
different files to be encrypted differently; see `Per-file encryption
keys`_ and `DIRECT_KEY policies`_.
Data path changes
-----------------
When inline encryption is used, filesystems just need to associate
encryption contexts with bios to specify how the block layer or the
inline encryption hardware will encrypt/decrypt the file contents.
When inline encryption isn't used, filesystems must encrypt/decrypt
the file contents themselves, as described below:
For the read path (->read_folio()) of regular files, filesystems can
read the ciphertext into the page cache and decrypt it in-place. The
folio lock must be held until decryption has finished, to prevent the
folio from becoming visible to userspace prematurely.
For the write path (->writepages()) of regular files, filesystems
cannot encrypt data in-place in the page cache, since the cached
plaintext must be preserved. Instead, filesystems must encrypt into a
temporary buffer or "bounce page", then write out the temporary
buffer. Some filesystems, such as UBIFS, already use temporary
buffers regardless of encryption. Other filesystems, such as ext4 and
F2FS, have to allocate bounce pages specially for encryption.
Filename hashing and encoding
-----------------------------
Modern filesystems accelerate directory lookups by using indexed
directories. An indexed directory is organized as a tree keyed by
filename hashes. When a ->lookup() is requested, the filesystem
normally hashes the filename being looked up so that it can quickly
find the corresponding directory entry, if any.
With encryption, lookups must be supported and efficient both with and
without the encryption key. Clearly, it would not work to hash the
plaintext filenames, since the plaintext filenames are unavailable
without the key. (Hashing the plaintext filenames would also make it
impossible for the filesystem's fsck tool to optimize encrypted
directories.) Instead, filesystems hash the ciphertext filenames,
i.e. the bytes actually stored on-disk in the directory entries. When
asked to do a ->lookup() with the key, the filesystem just encrypts
the user-supplied name to get the ciphertext.
Lookups without the key are more complicated. The raw ciphertext may
contain the ``\0`` and ``/`` characters, which are illegal in
filenames. Therefore, readdir() must base64url-encode the ciphertext
for presentation. For most filenames, this works fine; on ->lookup(),
the filesystem just base64url-decodes the user-supplied name to get
back to the raw ciphertext.
However, for very long filenames, base64url encoding would cause the
filename length to exceed NAME_MAX. To prevent this, readdir()
actually presents long filenames in an abbreviated form which encodes
a strong "hash" of the ciphertext filename, along with the optional
filesystem-specific hash(es) needed for directory lookups. This
allows the filesystem to still, with a high degree of confidence, map
the filename given in ->lookup() back to a particular directory entry
that was previously listed by readdir(). See
struct fscrypt_nokey_name in the source for more details.
Note that the precise way that filenames are presented to userspace
without the key is subject to change in the future. It is only meant
as a way to temporarily present valid filenames so that commands like
``rm -r`` work as expected on encrypted directories.
Tests
=====
To test fscrypt, use xfstests, which is Linux's de facto standard
filesystem test suite. First, run all the tests in the "encrypt"
group on the relevant filesystem(s). One can also run the tests
with the 'inlinecrypt' mount option to test the implementation for
inline encryption support. For example, to test ext4 and
f2fs encryption using `kvm-xfstests
<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>`_::
kvm-xfstests -c ext4,f2fs -g encrypt
kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
UBIFS encryption can also be tested this way, but it should be done in
a separate command, and it takes some time for kvm-xfstests to set up
emulated UBI volumes::
kvm-xfstests -c ubifs -g encrypt
No tests should fail. However, tests that use non-default encryption
modes (e.g. generic/549 and generic/550) will be skipped if the needed
algorithms were not built into the kernel's crypto API. Also, tests
that 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 also
possible to run most xfstests with the "test_dummy_encryption" mount
option. This option causes all new files to be automatically
encrypted with a dummy key, without having to make any API calls.
This tests the encrypted I/O paths more thoroughly. To do this with
kvm-xfstests, use the "encrypt" filesystem configuration::
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
Because this runs many more tests than "-g encrypt" does, it takes
much longer to run; so also consider using `gce-xfstests
<https://github.com/tytso/xfstests-bld/blob/master/Documentation/gce-xfstests.md>`_
instead of kvm-xfstests::
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
파일시스템 수준 암호화의 역할과 적용 범위
1-49fscrypt는 파일시스템이 연결해 파일과 디렉터리의 투명 암호화를 제공할 수 있게 하는 커널 라이브러리입니다. 이 문서에서 `fscrypt`는 사용자 공간 도구가 아니라 `fs/crypto/`에 구현된 커널 부분을 뜻합니다. 명령행 사용법은 사용자 공간 `fscrypt` 문서를 참고해야 합니다.
커널 API를 직접 호출하기보다는 `fscrypt`, `fscryptctl`, Android 키 관리 시스템 같은 검증된 사용자 공간 도구를 사용하는 것이 권장됩니다. 기존 도구는 자체 키 관리 코드를 작성하면서 보안 결함을 만들 가능성을 줄입니다. 다만 완전성을 위해 이 문서는 커널 API도 모두 설명합니다.
dm-crypt가 블록 장치 전체를 암호화하는 것과 달리 fscrypt는 파일시스템 계층에서 동작합니다. 따라서 파일마다 다른 키를 쓸 수 있고 같은 파일시스템 안에 평문 파일과 암호화 파일을 함께 둘 수 있습니다. 사용자별 저장 데이터를 암호학적으로 분리해야 하는 다중 사용자 시스템에 유용하지만, 파일 이름을 제외한 파일 크기·권한·시간 같은 파일시스템 메타데이터는 암호화하지 않습니다.
스택형 파일시스템인 eCryptfs와 달리 fscrypt는 ext4, F2FS, UBIFS, CephFS에 직접 통합됩니다. 평문 페이지와 암호문 페이지를 페이지 캐시에 이중 보관하지 않으므로 메모리 사용량을 거의 절반으로 줄이고, dentry와 inode도 절반만 필요합니다. eCryptfs의 암호화 파일 이름 한도는 143바이트이지만 fscrypt는 `NAME_MAX`인 255바이트를 허용합니다. 권한 없는 사용자도 별도 마운트 없이 API를 사용할 수 있습니다.
fscrypt는 기존 파일의 제자리 암호화를 지원하지 않습니다. 먼저 비어 있는 디렉터리에 암호화 정책을 설정하고 사용자 공간이 키를 제공해야 합니다. 그 뒤 해당 트리에 새로 생성되는 일반 파일, 디렉터리, 심볼릭 링크가 투명하게 암호화됩니다.
빈 디렉터리에 정책과 키를 결합해 새 객체부터 암호화하는 흐름입니다.
=====================================
Filesystem-level encryption (fscrypt)
=====================================
Introduction
============
fscrypt is a library which filesystems can hook into to support
transparent encryption of files and directories.
Note: "fscrypt" in this document refers to the kernel-level portion,
implemented in ``fs/crypto/``, as opposed to the userspace tool
`fscrypt <https://github.com/google/fscrypt>`_. This document only
covers the kernel-level portion. For command-line examples of how to
use encryption, see the documentation for the userspace tool `fscrypt
<https://github.com/google/fscrypt>`_. Also, it is recommended to use
the fscrypt userspace tool, or other existing userspace tools such as
`fscryptctl <https://github.com/google/fscryptctl>`_ or `Android's key
management system
<https://source.android.com/security/encryption/file-based>`_, over
using the kernel's API directly. Using existing tools reduces the
chance of introducing your own security bugs. (Nevertheless, for
completeness this documentation covers the kernel's API anyway.)
Unlike dm-crypt, fscrypt operates at the filesystem level rather than
at the block device level. This allows it to encrypt different files
with different keys and to have unencrypted files on the same
filesystem. This is useful for multi-user systems where each user's
data-at-rest needs to be cryptographically isolated from the others.
However, except for filenames, fscrypt does not encrypt filesystem
metadata.
Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated
directly into supported filesystems --- currently ext4, F2FS, UBIFS,
and CephFS. This allows encrypted files to be read and written
without caching both the decrypted and encrypted pages in the
pagecache, thereby nearly halving the memory used and bringing it in
line with unencrypted files. Similarly, half as many dentries and
inodes are needed. eCryptfs also limits encrypted filenames to 143
bytes, causing application compatibility issues; fscrypt allows the
full 255 bytes (NAME_MAX). Finally, unlike eCryptfs, the fscrypt API
can be used by unprivileged users, with no need to mount anything.
fscrypt does not support encrypting files in-place. Instead, it
supports marking an empty directory as encrypted. Then, after
userspace provides the key, all regular files, directories, and
symbolic links created in that directory tree are transparently
encrypted.
위협 모델과 v1 정책의 한계
50-193강한 암호화 키를 선택했다는 전제에서 fscrypt는 블록 장치 내용이 특정 한 시점에 영구적으로 오프라인 유출되었을 때 파일 내용과 파일 이름의 기밀성을 보호합니다. 파일 크기, 권한, 타임스탬프, 확장 속성 같은 파일 이름 외 메타데이터와 파일의 hole 위치·존재는 숨기지 않습니다.
공격자가 파일시스템을 오프라인으로 조작한 뒤 권한 있는 사용자가 나중에 그 파일시스템에 접근하게 만들 수 있다면 기밀성이나 무결성을 보장하지 않습니다. 저장장치 암호화 전반과 마찬가지로 온라인 공격에 대한 보호도 제한적입니다.
타이밍·전자기파 같은 부채널 공격 저항성은 Linux Crypto API 구현이나 인라인 암호화 하드웨어의 저항성만큼만 강합니다. 테이블 기반 AES처럼 취약한 구현을 쓰면 온라인 시스템을 상대로 부채널 공격이 가능할 수 있고, 복호화 데이터를 소비하는 애플리케이션도 공격 대상이 됩니다.
키가 추가된 뒤에는 같은 시스템의 다른 사용자에게 평문 파일 내용이나 이름을 fscrypt 자체가 숨기지 않습니다. 파일 모드 비트, POSIX ACL, LSM, namespace 같은 기존 접근 제어를 사용해야 합니다. 키가 있는 동안 시스템 관점의 기밀성은 암호 수학이 아니라 커널의 정확성에 의존하므로, 별도의 암호화 전용 접근 검사는 기존 커널 접근 제어와 대부분 중복됩니다.
hardware-wrapped key를 쓰지 않는다면 임의 커널 메모리를 읽을 수 있는 공격자는 현재 사용 중인 모든 fscrypt 키를 탈취할 수 있습니다. 갑작스러운 전원 차단 뒤 메모리에 키가 잠시 남을 수 있는 cold boot 공격도 포함됩니다. hardware-wrapped key는 master key와 파일 내용 암호화 키를 보호하지만 파일 이름 키 같은 다른 하위 키까지 보호하지는 않습니다.
`FS_IOC_REMOVE_ENCRYPTION_KEY` 또는 `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`는 커널 메모리의 master key를 지우고, 그 키로 잠금 해제된 캐시 inode를 퇴거시켜 per-file key도 지우려 합니다. 그러나 사용 중인 파일의 per-file key는 제거되지 않으므로 파일과 디렉터리를 닫고, 영향을 받는 암호화 디렉터리를 작업 디렉터리로 쓰는 프로세스도 종료해야 효과가 가장 큽니다.
커널은 사용자 공간이 가진 master key 복사본을 지울 수 없습니다. 사용자 공간은 `FS_IOC_ADD_ENCRYPTION_KEY` 직후 자체 복사본을 지우고, 더 상위 키 계층의 비밀도 같은 방식으로 처리해야 합니다. 키가 swap으로 나가지 않도록 `mlock()` 같은 방어도 적용해야 합니다.
VFS 캐시에 있던 복호화 내용과 파일 이름은 해제되지만 일반적으로 덮어쓰지는 않으므로, 키를 지운 뒤에도 해제 메모리에서 일부를 복구할 수 있습니다. 커널 명령행의 `init_on_free=1`로 일부 완화할 수 있지만 성능 비용이 있습니다. 비밀 키가 CPU 레지스터나 여기서 명시하지 않은 다른 위치에 남을 가능성도 있습니다.
root 권한 또는 임의 커널 코드 실행 권한을 얻은 공격자는 사용 중인 fscrypt 키로 보호되는 데이터를 자유롭게 유출할 수 있으므로 일반적으로 전체 시스템 침해 상황에서는 의미 있는 보호를 제공하지 못합니다. 공격 내내 키가 없었던 데이터는 키 제거의 한계를 제외하면 계속 보호됩니다.
hardware-wrapped key를 쓰면 전체 시스템을 침해한 공격자도 전원을 끈 뒤 사용할 수 있는 형태로 master key나 파일 내용 키를 반출할 수 없습니다. 공격자의 시간이나 대역폭이 크게 제한되어 일부 데이터만 온라인으로 빼내고 나머지는 나중의 오프라인 공격에 의존해야 하는 상황에서 유용할 수 있습니다.
v1 정책은 제공된 master key가 올바른지 검증하지 않습니다. 악의적 사용자가 읽기 전용으로 접근 가능한 다른 사용자의 암호화 파일에 잠시 잘못된 키를 연결하면 파일시스템 캐시 때문에 실제 사용자의 올바른 keyring보다 잘못된 키가 계속 사용될 수 있어 읽기 전용 접근 의미를 깨뜨립니다. 또한 per-file key 하나가 노출되면 그 기반 master key도 노출되고, 비root 사용자는 키를 안전하게 제거할 수 없습니다. v2 정책은 이 문제를 모두 해결하므로 새 암호화 디렉터리에는 v2를 권장합니다.
공격 유형별 보호 범위와 운영상 주의점입니다.
Threat model
============
Offline attacks
---------------
Provided that userspace chooses a strong encryption key, fscrypt
protects the confidentiality of file contents and filenames in the
event of a single point-in-time permanent offline compromise of the
block device content. fscrypt does not protect the confidentiality of
non-filename metadata, e.g. file sizes, file permissions, file
timestamps, and extended attributes. Also, the existence and location
of holes (unallocated blocks which logically contain all zeroes) in
files is not protected.
fscrypt is not guaranteed to protect confidentiality or authenticity
if an attacker is able to manipulate the filesystem offline prior to
an authorized user later accessing the filesystem.
Online attacks
--------------
fscrypt (and storage encryption in general) can only provide limited
protection against online attacks. In detail:
Side-channel attacks
~~~~~~~~~~~~~~~~~~~~
fscrypt is only resistant to side-channel attacks, such as timing or
electromagnetic attacks, to the extent that the underlying Linux
Cryptographic API algorithms or inline encryption hardware are. If a
vulnerable algorithm is used, such as a table-based implementation of
AES, it may be possible for an attacker to mount a side channel attack
against the online system. Side channel attacks may also be mounted
against applications consuming decrypted data.
Unauthorized file access
~~~~~~~~~~~~~~~~~~~~~~~~
After an encryption key has been added, fscrypt does not hide the
plaintext file contents or filenames from other users on the same
system. Instead, existing access control mechanisms such as file mode
bits, POSIX ACLs, LSMs, or namespaces should be used for this purpose.
(For the reasoning behind this, understand that while the key is
added, the confidentiality of the data, from the perspective of the
system itself, is *not* protected by the mathematical properties of
encryption but rather only by the correctness of the kernel.
Therefore, any encryption-specific access control checks would merely
be enforced by kernel *code* and therefore would be largely redundant
with the wide variety of access control mechanisms already available.)
Read-only kernel memory compromise
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unless `hardware-wrapped keys`_ are used, an attacker who gains the
ability to read from arbitrary kernel memory, e.g. by mounting a
physical attack or by exploiting a kernel security vulnerability, can
compromise all fscrypt keys that are currently in-use. This also
extends 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 master
keys and file contents encryption keys (but not other types of fscrypt
subkeys such as filenames encryption keys) are protected from
compromises of arbitrary kernel memory.
In addition, fscrypt allows encryption keys to be removed from the
kernel, which may protect them from later compromise.
In more detail, the FS_IOC_REMOVE_ENCRYPTION_KEY ioctl (or the
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS ioctl) can wipe a master
encryption key from kernel memory. If it does so, it will also try to
evict 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 will *not* be removed or wiped.
Therefore, for maximum effect, userspace should close the relevant
encrypted files and directories before removing a master key, as
well as kill any processes whose working directory is in an affected
encrypted directory.
- The kernel cannot magically wipe copies of the master key(s) that
userspace might have as well. Therefore, userspace must wipe all
copies of the master key(s) it makes as well; normally this should
be done immediately after FS_IOC_ADD_ENCRYPTION_KEY, without waiting
for FS_IOC_REMOVE_ENCRYPTION_KEY. Naturally, the same also applies
to all higher levels in the key hierarchy. Userspace should also
follow other security precautions such as mlock()ing memory
containing keys to prevent it from being swapped out.
- In general, decrypted contents and filenames in the kernel VFS
caches are freed but not wiped. Therefore, portions thereof may be
recoverable from freed memory, even after the corresponding key(s)
were wiped. To partially solve this, you can add init_on_free=1 to
your kernel command line. However, this has a performance cost.
- Secret keys might still exist in CPU registers or in other places
not explicitly considered here.
Full system compromise
~~~~~~~~~~~~~~~~~~~~~~
An attacker who gains "root" access and/or the ability to execute
arbitrary kernel code can freely exfiltrate data that is protected by
any in-use fscrypt keys. Thus, usually fscrypt provides no meaningful
protection in this scenario. (Data that is protected by a key that is
absent throughout the entire attack remains protected, modulo the
limitations of key removal mentioned above in the case where the key
was removed prior to the attack.)
However, if `hardware-wrapped keys`_ are used, such attackers will be
unable to exfiltrate the master keys or file contents keys in a form
that will be usable after the system is powered off. This may be
useful if the attacker is significantly time-limited and/or
bandwidth-limited, so they can only exfiltrate some data and need to
rely on a later offline attack to exfiltrate the rest of it.
Limitations of v1 policies
~~~~~~~~~~~~~~~~~~~~~~~~~~
v1 encryption policies have some weaknesses with respect to online
attacks:
- There is no verification that the provided master key is correct.
Therefore, a malicious user can temporarily associate the wrong key
with another user's encrypted files to which they have read-only
access. Because of filesystem caching, the wrong key will then be
used by the other user's accesses to those files, even if the other
user has the correct key in their own keyring. This violates the
meaning of "read-only access".
- A compromise of a per-file key also compromises the master key from
which it was derived.
- Non-root users cannot securely remove encryption keys.
All the above problems are fixed with v2 encryption policies. For
this reason among others, it is recommended to use v2 encryption
policies on all new encrypted directories.
Master key, KDF, per-file key와 IV 정책
194-355이 절은 raw key 사용을 전제로 합니다. hardware-wrapped key를 쓰면 키 계층이 일부 달라집니다. 각 암호화 디렉터리 트리는 하나의 master key로 보호되며 master key는 최대 64바이트입니다. 내용 모드와 파일 이름 모드 중 더 강한 보안 강도 이상이어야 하므로 AES-256 모드가 하나라도 있으면 최소 32바이트가 필요합니다. v1 정책에서 AES-256-XTS를 쓰는 경우에는 64바이트가 필요합니다.
사용자 공간은 디렉터리 트리를 잠금 해제할 올바른 master key를 제공합니다. master key 수에는 제한이 없고, 하나의 키가 여러 파일시스템에 걸친 여러 디렉터리 트리를 보호할 수 있습니다.
master key는 같은 길이의 무작위 바이트열과 구별할 수 없는 실제 암호 키여야 합니다. 암호를 그대로 사용하거나 짧은 키를 0으로 채우거나 반복해서는 안 됩니다. CSPRNG로 생성하거나 KDF로 만들어야 합니다. 커널은 key stretching을 하지 않으므로 passphrase 같은 저엔트로피 비밀에서 만들 때는 `scrypt`, `PBKDF2`, `Argon2`처럼 그 목적에 맞는 KDF가 필수입니다.
한 가지 예외를 제외하면 fscrypt는 master key를 직접 암호화에 쓰지 않고 KDF 입력으로만 씁니다. v1과 v2는 KDF가 다르므로 같은 키를 두 정책 버전에 재사용해서는 안 됩니다. 이 특정 재사용에 알려진 현실 공격이 없더라도 암호학적 증명과 분석이 더 이상 적용되지 않습니다.
v1 KDF는 per-file encryption key만 파생합니다. 파일의 16바이트 nonce를 AES 키로 삼아 AES-128-ECB로 master key를 암호화하고, 결과 암호문이 필요한 길이보다 길면 잘라 사용합니다. 이 방식은 임의 설계이고 가역적입니다.
v2는 HKDF-SHA512를 사용합니다. master key를 input keying material로 넣고 salt는 쓰지 않으며, 파생할 키 종류마다 다른 application-specific information string을 사용합니다. per-file key의 정보 문자열은 `fscrypt\0`, context byte, 파일 nonce로 구성되고 다른 하위 키에는 다른 context byte를 씁니다. HKDF는 더 유연하고 비가역적이며 master key 엔트로피를 고르게 분배하고 표준화되어 있어 v1 방식보다 선호됩니다.
새 암호화 inode가 생성되면 커널은 무작위 16바이트 nonce를 만들어 inode의 암호화 xattr에 저장하고 master key와 nonce에서 파일 키를 파생합니다. 같은 평문이 서로 다른 파일에서 같은 암호문이 되는 것을 막는 tweak 역할을 합니다. 키 래핑보다 파생을 택한 이유는 wrapped key가 xattr을 키워 inode table에 inline으로 들어갈 가능성을 낮추는 반면, 현재 여러 master key로 같은 파일을 열거나 master key를 회전할 요구는 없기 때문입니다. master key 자체는 사용자 공간에서 래핑할 수 있습니다.
Adiantum은 내용과 파일 이름 모두에 쓸 수 있고 8바이트 data unit index와 16바이트 per-file nonce를 함께 담는 긴 IV를 받습니다. 키 하나의 오버헤드도 AES-256-XTS보다 큽니다. `FSCRYPT_POLICY_FLAG_DIRECT_KEY`를 설정하면 per-file key를 만들지 않고 파일 nonce를 모든 내용·이름 암호화 IV에 포함합니다.
DIRECT_KEY를 v1에서 사용하면 master key 자체로 암호화하므로 그 키를 다른 v1 정책을 포함한 어떤 용도로도 재사용하면 안 됩니다. v2에서는 KDF로 파생한 per-mode key를 쓰므로 같은 master key를 다른 v2 정책에 재사용할 수 있습니다.
`FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64`에서는 master key, 암호화 모드 번호, 파일시스템 UUID로 키를 파생합니다. 보통 같은 master key의 모든 파일이 하나의 내용 키와 하나의 이름 키를 공유하고, 파일별 차이는 IV에 inode 번호를 넣어 확보합니다. 이 때문에 파일시스템 축소가 허용되지 않을 수 있습니다. UFS 표준처럼 요청당 IV가 64비트뿐이고 keyslot이 적은 인라인 암호화 하드웨어에 최적화된 형식입니다.
`IV_INO_LBLK_32`도 같은 계열이지만 master key에서 파생한 SipHash 키로 inode 번호를 SipHash-2-4 해시한 뒤 파일 data unit index를 더하고 mod 2^32를 취해 32비트 IV를 만듭니다. eMMC v5.2처럼 요청당 IV 32비트와 적은 keyslot만 지원하는 하드웨어용입니다. 어느 정도 IV 재사용이 발생하므로 하드웨어 제약 때문에 필요할 때만 사용해야 합니다.
v2 master key에는 KDF로 고유한 16바이트 key identifier도 파생하며, 키를 안정적으로 식별해야 하므로 평문으로 저장합니다. 평문 파일 이름에 secret-keyed dirhash를 쓰는 디렉터리는 디렉터리마다 128비트 SipHash-2-4 키를 다른 KDF context로 파생합니다. 현재 이 방식은 casefolded, 즉 대소문자를 구분하지 않는 암호화 디렉터리만 사용합니다.
master key에서 정책과 inode별 하위 키가 갈라지는 관계입니다.
파일별 분리 방법과 하드웨어 목적을 비교합니다.
Key hierarchy
=============
Note: this section assumes the use of raw keys rather than
hardware-wrapped keys. The use of hardware-wrapped keys modifies the
key hierarchy slightly. For details, see `Hardware-wrapped keys`_.
Master Keys
-----------
Each encrypted directory tree is protected by a *master key*. Master
keys can be up to 64 bytes long, and must be at least as long as the
greater of the security strength of the contents and filenames
encryption modes being used. For example, if any AES-256 mode is
used, the master key must be at least 256 bits, i.e. 32 bytes. A
stricter requirement applies if the key is used by a v1 encryption
policy and AES-256-XTS is used; such keys must be 64 bytes.
To "unlock" an encrypted directory tree, userspace must provide the
appropriate master key. There can be any number of master keys, each
of which protects any number of directory trees on any number of
filesystems.
Master keys must be real cryptographic keys, i.e. indistinguishable
from random bytestrings of the same length. This implies that users
**must not** directly use a password as a master key, zero-pad a
shorter key, or repeat a shorter key. Security cannot be guaranteed
if userspace makes any such error, as the cryptographic proofs and
analysis would no longer apply.
Instead, users should generate master keys either using a
cryptographically 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 such
as a passphrase, it is critical that a KDF designed for this purpose
be used, such as scrypt, PBKDF2, or Argon2.
Key derivation function
-----------------------
With one exception, fscrypt never uses the master key(s) for
encryption 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 whether
the key is used for v1 encryption policies or for v2 encryption
policies. Users **must not** use the same key for both v1 and v2
encryption policies. (No real-world attack is currently known on this
specific case of key reuse, but its security cannot be guaranteed
since the cryptographic proofs and analysis would no longer apply.)
For v1 encryption policies, the KDF only supports deriving per-file
encryption keys. It works by encrypting the master key with
AES-128-ECB, using the file's 16-byte nonce as the AES key. The
resulting ciphertext is used as the derived key. If the ciphertext is
longer than needed, then it is truncated to the needed length.
For v2 encryption policies, the KDF is HKDF-SHA512. The master key is
passed as the "input keying material", no salt is used, and a distinct
"application-specific information string" is used for each distinct
key to be derived. For example, when a per-file encryption key is
derived, the application-specific information string is the file's
nonce prefixed with "fscrypt\\0" and a context byte. Different
context bytes are used for other types of derived keys.
HKDF-SHA512 is preferred to the original AES-128-ECB based KDF because
HKDF is more flexible, is nonreversible, and evenly distributes
entropy from the master key. HKDF is also standardized and widely
used 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 two
files doesn't map to the same ciphertext, or vice versa. In most
cases, fscrypt does this by deriving per-file keys. When a new
encrypted inode (regular file, directory, or symlink) is created,
fscrypt randomly generates a 16-byte nonce and stores it in the
inode's encryption xattr. Then, it uses a KDF (as described in `Key
derivation function`_) to derive the file's key from the master key
and nonce.
Key derivation was chosen over key wrapping because wrapped keys would
require larger xattrs which would be less likely to fit in-line in the
filesystem's inode table, and there didn't appear to be any
significant advantages to key wrapping. In particular, currently
there is no requirement to support unlocking a file with multiple
alternative master keys or to support rotating master keys. Instead,
the master keys may be wrapped in userspace, e.g. as is done by the
`fscrypt <https://github.com/google/fscrypt>`_ tool.
DIRECT_KEY policies
-------------------
The Adiantum encryption mode (see `Encryption modes and usage`_) is
suitable for both contents and filenames encryption, and it accepts
long IVs --- long enough to hold both an 8-byte data unit index and a
16-byte per-file nonce. Also, the overhead of each Adiantum key is
greater 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 enabled
this 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 is
included in the IV. Moreover:
- For v1 encryption policies, the encryption is done directly with the
master key. Because of this, users **must not** use the same master
key for any other purpose, even for other v1 policies.
- For v2 encryption policies, the encryption is done with a per-mode
key derived using the KDF. Users may use the same master key for
other 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 mode
number, and filesystem UUID. This normally results in all files
protected by the same master key sharing a single contents encryption
key and a single filenames encryption key. To still encrypt different
files' 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 hardware
compliant with the UFS standard, which supports only 64 IV bits per
I/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 for
IV_INO_LBLK_32, the inode number is hashed with SipHash-2-4 (where the
SipHash key is derived from the master key) and added to the file data
unit index mod 2^32 to produce a 32-bit IV.
This format is optimized for use with inline encryption hardware
compliant with the eMMC v5.2 standard, which supports only 32 IV bits
per I/O request and may have only a small number of keyslots. This
format results in some level of IV reuse, so it should only be used
when necessary due to hardware limitations.
Key identifiers
---------------
For master keys used for v2 encryption policies, a unique 16-byte "key
identifier" is also derived using the KDF. This value is stored in
the clear, since it is needed to reliably identify the key itself.
Dirhash keys
------------
For directories that are indexed using a secret-keyed dirhash over the
plaintext filenames, the KDF is also used to derive a 128-bit
SipHash-2-4 key per directory in order to hash filenames. This works
just like deriving a per-file encryption key, except that a different
KDF context is used. Currently, only casefolded ("case-insensitive")
encrypted directories use this style of hashing.
지원 암호화 모드와 커널 구성
356-472fscrypt는 파일 내용용 모드 하나와 파일 이름용 모드 하나를 정책에 지정하며 디렉터리 트리마다 다른 조합을 쓸 수 있습니다. 지원 조합은 AES-256-XTS/AES-256-CBC-CTS, AES-256-XTS/AES-256-HCTR2, 내용·이름 모두 Adiantum, AES-128-CBC-ESSIV/AES-128-CBC-CTS, SM4-XTS/SM4-CBC-CTS입니다. API 이름에서 `CBC`는 CBC-ESSIV, `CTS`는 CBC-CTS를 뜻하므로 `FSCRYPT_MODE_AES_256_CTS`는 AES-256-CBC-CTS입니다.
암호문 길이 증가를 다루기 어려워 authenticated encryption mode는 현재 지원하지 않습니다. 내용은 XTS, CBC-ESSIV 또는 wide-block cipher를 사용하고, 파일 이름은 CBC-CTS 또는 wide-block cipher를 사용합니다.
권장 기본 조합은 AES-256-XTS/AES-256-CBC-CTS입니다. 커널이 fscrypt를 지원한다면 항상 지원된다고 보장되는 유일한 선택입니다. AES-256-XTS/AES-256-HCTR2는 파일 이름을 wide-block cipher로 업그레이드하는 좋은 선택입니다. wide-block cipher는 한 비트가 바뀌면 결과 전체가 뒤섞이는 tweakable super-pseudorandom permutation이므로 파일 이름 문제에 이상적이고, CBC-CTS는 대안 중 덜 나쁜 선택입니다.
AES 하드웨어 가속이 없어 AES가 느린 시스템에는 Adiantum을 권장합니다. Adiantum은 XChaCha12와 AES-256을 구성 요소로 사용하는 wide-block cipher이며 대부분의 작업을 XChaCha12가 수행하므로 AES 가속이 없을 때 훨씬 빠릅니다.
AES-128-CBC-ESSIV/AES-128-CBC-CTS 조합은 CPU AES 명령은 없지만 AES-CBC를 지원하고 AES-XTS는 지원하지 않는 CAAM·CESA 같은 비인라인 crypto engine을 위해 추가되었습니다. 그러나 CPU에서 AES를 직접 수행하는 편이 더 빠르고 Adiantum은 더 빠르다는 것이 확인되어 폐기 예정입니다.
SM4 조합은 국가 표준 준수가 요구되는 용도를 위한 선택이며, 다른 선택보다 암호 분석 검토가 제한적이므로 SM4가 의무인 경우에만 사용해야 합니다.
`CONFIG_FS_ENCRYPTION`은 AES-256-XTS와 AES-256-CBC-CTS를 포함한 기본 fscrypt 지원을 선택합니다. 최적 성능을 위해 CPU별 암호 가속을 켜야 합니다. 내용 암호화가 인라인 하드웨어에서 처리된다면 그 내용 모드가 Crypto API에 없어도 되지만, 파일 이름 모드는 여전히 Crypto API 구현이 필요합니다.
AES 기본 조합은 arm64에서 `CONFIG_CRYPTO_AES_ARM64_CE_BLK`, x86에서 `CONFIG_CRYPTO_AES_NI_INTEL`을 권장합니다. HCTR2에는 `CONFIG_CRYPTO_HCTR2`가 필수이며 플랫폼 AES와 POLYVAL 가속을 권장합니다. Adiantum에는 `CONFIG_CRYPTO_ADIANTUM`이 필수이고 NHPOLY1305의 NEON, SSE2, AVX2 구현을 플랫폼에 맞게 권장합니다. AES-128-CBC-ESSIV에는 `CONFIG_CRYPTO_ESSIV`, SHA-256과 AES-CBC 가속이 필요합니다.
내용과 파일 이름에 허용되는 짝과 권장 용도입니다.
모드별 필수·권장 구성입니다.
Encryption modes and usage
==========================
fscrypt allows one encryption mode to be specified for file contents
and one encryption mode to be specified for filenames. Different
directory 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 of
the difficulty of dealing with ciphertext expansion. Therefore,
contents encryption uses a block cipher in `XTS mode
<https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS>`_ or
`CBC-ESSIV mode
<https://en.wikipedia.org/wiki/Disk_encryption_theory#Encrypted_salt-sector_initialization_vector_(ESSIV)>`_,
or a wide-block cipher. Filenames encryption uses a
block cipher in `CBC-CTS mode
<https://en.wikipedia.org/wiki/Ciphertext_stealing>`_ or a wide-block
cipher.
The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default.
It is also the only option that is *guaranteed* to always be supported
if the kernel supports fscrypt at all; see `Kernel config options`_.
The (AES-256-XTS, AES-256-HCTR2) pair is also a good choice that
upgrades the filenames encryption to use a wide-block cipher. (A
*wide-block cipher*, also called a tweakable super-pseudorandom
permutation, has the property that changing one bit scrambles the
entire result.) As described in `Filenames encryption`_, a wide-block
cipher is the ideal mode for the problem domain, though CBC-CTS is the
"least bad" choice among the alternatives. For more information about
HCTR2, see `the HCTR2 paper <https://eprint.iacr.org/2021/1441.pdf>`_.
Adiantum is recommended on systems where AES is too slow due to lack
of hardware acceleration for AES. Adiantum is a wide-block cipher
that uses XChaCha12 and AES-256 as its underlying components. Most of
the work is done by XChaCha12, which is much faster than AES when AES
acceleration is unavailable. For more information about Adiantum, see
`the Adiantum paper <https://eprint.iacr.org/2018/720.pdf>`_.
The (AES-128-CBC-ESSIV, AES-128-CBC-CTS) pair was added to try to
provide a more efficient option for systems that lack AES instructions
in the CPU but do have a non-inline crypto engine such as CAAM or CESA
that supports AES-CBC (and not AES-XTS). This is deprecated. It has
been 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 they
receive limited security review compared to the usual choices such as
AES and ChaCha. They also don't bring much new to the table. It is
suggested to only use these ciphers where their use is mandated.
Kernel config options
---------------------
Enabling fscrypt support (CONFIG_FS_ENCRYPTION) automatically pulls in
only the basic support from the crypto API needed to use AES-256-XTS
and AES-256-CBC-CTS encryption. For optimal performance, it is
strongly recommended to also enable any available platform-specific
kconfig options that provide acceleration for the algorithm(s) you
wish to use. Support for any "non-default" encryption modes typically
requires extra kconfig options as well.
Below, some relevant options are listed by encryption mode. Note,
acceleration options not listed below may be available for your
platform; refer to the kconfig menus. File contents encryption can
also be configured to use inline encryption hardware instead of the
kernel crypto API (see `Inline encryption support`_); in that case,
the file contents mode doesn't need to supported in the kernel crypto
API, 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
파일 내용과 파일 이름 암호화 방식
473-566파일 내용은 독립적으로 암복호화되는 data unit으로 나뉘며 IV에는 파일 안에서 0부터 시작하는 data unit index가 포함됩니다. 따라서 암호화 파일에서 `FALLOC_FL_COLLAPSE_RANGE`와 `FALLOC_FL_INSERT_RANGE`처럼 data unit 위치를 바꾸는 연산은 지원하지 않습니다.
UBIFS를 제외한 파일시스템은 고정 크기 data unit을 사용합니다. 기본 크기는 파일시스템 블록 크기이고 v2 정책의 `log2_data_unit_size`로 더 작은 지원 크기를 선택할 수 있습니다. 마지막 unit은 0으로 채웁니다. UBIFS는 압축될 수 있는 가변 크기 data node를 단위로 쓰고 16바이트 배수로 패딩하며 sub-block data unit은 쓰지 않습니다.
압축을 지원하는 파일시스템에서는 압축 뒤 암호화합니다. F2FS 압축 파일도 고정 크기 data unit을 사용하며 압축되지 않은 범위나 hole과 일관되게 다룹니다.
기본 정책의 IV는 per-file key와 data unit index로 구성됩니다. DIRECT_KEY에서는 IV 비트 0~63에 index, 비트 64~191에 16바이트 nonce를 둡니다. IV_INO_LBLK_64에서는 비트 0~31에 index, 비트 32~63에 inode 번호를 넣으며 둘 다 32비트에 맞아야 합니다. IV_INO_LBLK_32에서는 해시된 inode 값과 index의 합을 32비트로 줄여 비트 0~31에 둡니다. 모든 정수는 little-endian으로 인코딩합니다.
AES-128-CBC 내용 모드는 ESSIV를 자동으로 적용합니다. contents key의 SHA-256 해시를 AES-256 키로 사용해 data unit index를 암호화한 값이 CBC IV가 됩니다.
파일 이름은 이름 전체를 하나의 암호화 단위로 처리합니다. 디렉터리 조회가 가능하고 `NAME_MAX` 255바이트를 지키기 위해 같은 디렉터리의 모든 이름에 같은 IV를 쓰지만, 기본 정책은 디렉터리별 키를 쓰고 DIRECT_KEY·inode IV 정책은 nonce나 inode를 IV에 포함해 파일 간 재사용을 제한합니다.
CBC-CTS는 16바이트 이상 공통 접두사를 가진 파일 이름에서 그 접두사를 누설합니다. HCTR2와 Adiantum 같은 wide-block 모드는 이 문제가 없습니다. 입력 길이는 최소 16바이트가 되도록 NUL로 채우며, 파일 이름은 정책에 따라 4·8·16·32바이트 배수로 패딩합니다. 32바이트 패딩을 권장합니다. 실제 파일 이름에는 NUL이 허용되지 않으므로 패딩 뒤에도 매핑은 고유합니다.
심볼릭 링크 대상은 파일 이름과 같은 방식으로 암호화하지만 심볼릭 링크 자체 inode의 키·nonce를 사용하므로 파일 이름과 IV가 재사용되지 않습니다.
정책별 IV 비트 구성을 구조화한 표입니다.
조회 가능성과 길이 제한을 함께 만족하는 처리 순서입니다.
Contents encryption
-------------------
For contents encryption, each file's contents is divided into "data
units". Each data unit is encrypted independently. The IV for each
data unit incorporates the zero-based index of the data unit within
the file. This ensures that each data unit within a file is encrypted
differently, which is essential to prevent leaking information.
Note: the encryption depending on the offset into the file means that
operations like "collapse range" and "insert range" that rearrange the
extent 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 UBIFS
work. A file's data units are all the same size; the last data unit
is zero-padded if needed. By default, the data unit size is equal
to the filesystem block size. On some filesystems, users can select
a sub-block data unit size via the ``log2_data_unit_size`` field of
the encryption policy; see `FS_IOC_SET_ENCRYPTION_POLICY`_.
* Variable-size data units. This is what UBIFS does. Each "UBIFS
data node" is treated as a crypto data unit. Each contains variable
length, possibly compressed data, zero-padded to the next 16-byte
boundary. Users cannot select a sub-block data unit size on UBIFS.
In the case of compression + encryption, the compressed data is
encrypted. UBIFS compression works as described above. f2fs
compression works a bit differently; it compresses a number of
filesystem blocks into a smaller number of filesystem blocks.
Therefore a f2fs-compressed file still uses fixed-size data units, and
it is encrypted in a similar way to a file containing holes.
As mentioned in `Key hierarchy`_, the default encryption setting uses
per-file keys. In this case, the IV for each data unit is simply the
index of the data unit in the file. However, users can select an
encryption setting that does not use per-file keys. For these, some
kind of file identifier is incorporated into the IVs as follows:
- With `DIRECT_KEY policies`_, the data unit index is placed in bits
0-63 of the IV, and the file's nonce is placed in bits 64-191.
- With `IV_INO_LBLK_64 policies`_, the data unit index is placed in
bits 0-31 of the IV, and the file's inode number is placed in bits
32-63. This setting is only allowed when data unit indices and
inode numbers fit in 32 bits.
- With `IV_INO_LBLK_32 policies`_, the file's inode number is hashed
and added to the data unit index. The resulting value is truncated
to 32 bits and placed in bits 0-31 of the IV. This setting is only
allowed 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, an
ESSIV layer is automatically included. In this case, before the IV is
passed to AES-128-CBC, it is encrypted with AES-256 where the AES-256
key is the SHA-256 hash of the file's contents encryption key.
Filenames encryption
--------------------
For filenames, each full filename is encrypted at once. Because of
the requirements to retain support for efficient directory lookups and
filenames of up to 255 bytes, the same IV is used for every filename
in a directory.
However, each encrypted directory still uses a unique key, or
alternatively has the file's nonce (for `DIRECT_KEY policies`_) or
inode number (for `IV_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 a
common prefix at least as long as the cipher block size (16 bytes for AES), the
corresponding encrypted filenames will also share a common prefix. This is
undesirable. Adiantum and HCTR2 do not have this weakness, as they are
wide-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 before
being encrypted. In addition, to reduce leakage of filename lengths
via their ciphertexts, all filenames are NUL-padded to the next 4, 8,
16, or 32-byte boundary (configurable). 32 is recommended since this
provides the best confidentiality, at the cost of making directory
entries consume slightly more space. Note that since NUL (``\0``) is
not otherwise a valid character in filenames, the padding will never
produce duplicate plaintexts.
Symbolic link targets are considered a type of filename and are
encrypted in the same way as filenames in directory entries, except
that IV reuse is not a problem as each symlink has its own inode.
암호화 정책 설정 API
567-742정책은 `FS_IOC_SET_ENCRYPTION_POLICY` ioctl로 비어 있는 디렉터리에 설정합니다. v1 구조체의 버전 값은 역사적 이유로 `FSCRYPT_POLICY_V1`인 0이고, v2 값은 `FSCRYPT_POLICY_V2`인 2입니다. 새 암호화 디렉터리에는 v2를 사용해야 합니다.
#define FSCRYPT_POLICY_V1 0
#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8
struct 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_V2 2
#define FSCRYPT_KEY_IDENTIFIER_SIZE 16
struct 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];
};
`contents_encryption_mode`와 `filenames_encryption_mode`에는 지원되는 모드 짝을 지정합니다. 일반 기본값은 내용 `FSCRYPT_MODE_AES_256_XTS`(1), 이름 `FSCRYPT_MODE_AES_256_CTS`(4)입니다. v1은 역사적으로 지원된 세 조합만 허용하고 v2는 현재 지원 조합 전체를 허용합니다.
`flags`의 `FSCRYPT_POLICY_FLAGS_PAD_4`, `_PAD_8`, `_PAD_16`, `_PAD_32`는 파일 이름 패딩을 선택하며 PAD_32를 권장합니다. `FSCRYPT_POLICY_FLAG_DIRECT_KEY`, `FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64`, `FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32`는 키·IV 구성을 선택하고 서로 동시에 사용할 수 없습니다. v1은 패딩과 DIRECT_KEY만 지원합니다.
v2의 `log2_data_unit_size`가 0이면 파일시스템 기본값을 사용하고, 예를 들어 12는 4096바이트를 뜻합니다. ext4와 F2FS는 Linux 6.7부터 기본값이 아닌 값을 지원합니다. 0이 아니라면 9 이상이고 파일시스템 블록 크기의 log2 이하여야 합니다. 인라인 하드웨어가 특정 단위를 요구할 때 사용할 수 있으며 sysfs의 crypto capability를 확인해야 합니다. 더 작은 단위는 성능을 낮출 수 있습니다. `__reserved`는 0이어야 합니다.
v1의 8바이트 `master_key_descriptor`는 사용자 공간이 키를 식별하도록 선택한 값입니다. e4crypt와 fscrypt 도구는 보통 master key에 SHA-512를 두 번 적용한 결과의 첫 8바이트를 사용하지만 커널이 강제하지는 않습니다. 정책 설정 시 키가 없어도 되지만 파일을 만들기 전에는 키가 필요합니다.
v2의 16바이트 `master_key_identifier`는 `FS_IOC_ADD_ENCRYPTION_KEY`가 반환한 값을 그대로 사용해야 하며 임의 값을 넣으면 안 됩니다. 정책을 설정하는 사용자가 현재 해당 키를 추가한 사용자이거나 초기 user namespace에서 `CAP_FOWNER`를 가져야 합니다. ioctl이 실행되는 동안 키는 제거되지 않도록 유지됩니다.
대상은 암호화되지 않은 빈 디렉터리여야 하며 이후 생성되는 자손이 정책을 상속합니다. 이미 암호화된 디렉터리에 같은 정책을 다시 설정하면 성공하고 다른 정책이면 `EEXIST`입니다. ext4 루트 디렉터리는 암호화할 수 없으므로 파일시스템 전체 보호가 필요하면 dm-crypt를 사용합니다.
오류는 접근·소유권 실패 `EACCES`, 기존 다른 정책 `EEXIST`, 구조체·버전·모드·플래그 오류 `EINVAL`, v2 키 부재 `ENOKEY`, 대상이 디렉터리가 아님 `ENOTDIR`, 비어 있지 않음 `ENOTEMPTY`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 `EOPNOTSUPP`, 권한 부족 `EPERM`, 읽기 전용 파일시스템 `EROFS` 등으로 구분됩니다.
v1과 v2의 차이와 초기화 규칙입니다.
실패 원인을 운영자가 구분할 수 있게 정리했습니다.
User API
========
Setting an encryption policy
----------------------------
FS_IOC_SET_ENCRYPTION_POLICY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on an
empty directory or verifies that a directory or regular file already
has the specified encryption policy. It takes in a pointer to
struct fscrypt_policy_v1 or struct fscrypt_policy_v2, defined as
follows::
#define FSCRYPT_POLICY_V1 0
#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8
struct 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 16
struct 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) if
struct fscrypt_policy_v1 is used or FSCRYPT_POLICY_V2 (2) if
struct fscrypt_policy_v2 is used. (Note: we refer to the original
policy version as "v1", though its version code is really 0.)
For new encrypted directories, use v2 policies.
- ``contents_encryption_mode`` and ``filenames_encryption_mode`` must
be set to constants from ``<linux/fscrypt.h>`` which identify the
encryption modes to use. If unsure, use FSCRYPT_MODE_AES_256_XTS
(1) for ``contents_encryption_mode`` and FSCRYPT_MODE_AES_256_CTS
(4) for ``filenames_encryption_mode``. For details, see `Encryption
modes 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 support
all combinations documented in `Supported modes`_.
- ``flags`` contains optional flags from ``<linux/fscrypt.h>``:
- FSCRYPT_POLICY_FLAGS_PAD_*: The amount of NUL padding to use when
encrypting filenames. If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32
(0x3).
- FSCRYPT_POLICY_FLAG_DIRECT_KEY: See `DIRECT_KEY policies`_.
- FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: See `IV_INO_LBLK_64
policies`_.
- FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: See `IV_INO_LBLK_32
policies`_.
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 are
mutually 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 is
the granularity of file contents encryption. For example, setting
``log2_data_unit_size`` to 12 causes file contents be passed to the
underlying encryption algorithm (such as AES-256-XTS) in 4096-byte
data units, each with its own IV.
Not all filesystems support setting ``log2_data_unit_size``. ext4
and f2fs support it since Linux v6.7. On filesystems that support
it, the supported nonzero values are 9 through the log2 of the
filesystem block size, inclusively. The default value of 0 selects
the filesystem block size.
The main use case for ``log2_data_unit_size`` is for selecting a
data unit size smaller than the filesystem block size for
compatibility with inline encryption hardware that only supports
smaller data unit sizes. ``/sys/block/$disk/queue/crypto/`` may be
useful for checking which data unit sizes are supported by a
particular system's inline encryption hardware.
Leave this field zeroed unless you are certain you need it. Using
an unnecessarily small data unit size reduces performance.
- For v2 encryption policies, ``__reserved`` must be zeroed.
- For v1 encryption policies, ``master_key_descriptor`` specifies how
to find the master key in a keyring; see `Adding keys`_. It is up
to userspace to choose a unique ``master_key_descriptor`` for each
master key. The e4crypt and fscrypt tools use the first 8 bytes of
``SHA-512(SHA-512(master_key))``, but this particular scheme is not
required. Also, the master key need not be in the keyring yet when
FS_IOC_SET_ENCRYPTION_POLICY is executed. However, it must be added
before any files can be created in the encrypted directory.
For v2 encryption policies, ``master_key_descriptor`` has been
replaced with ``master_key_identifier``, which is longer and cannot
be arbitrarily chosen. Instead, the key must first be added using
`FS_IOC_ADD_ENCRYPTION_KEY`_. Then, the ``key_spec.u.identifier``
the kernel returned in the struct fscrypt_add_key_arg must
be used as the ``master_key_identifier`` in
struct fscrypt_policy_v2.
If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY
verifies that the file is an empty directory. If so, the specified
encryption policy is assigned to the directory, turning it into an
encrypted directory. After that, and after providing the
corresponding master key as described in `Adding keys`_, all regular
files, directories (recursively), and symlinks created in the
directory 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, then
FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption
policy exactly matches the actual one. If they match, then the ioctl
returns 0. Otherwise, it fails with EEXIST. This works on both
regular files and directories, including nonempty directories.
When a v2 encryption policy is assigned to a directory, it is also
required that either the specified key has been added by the current
user or that the caller has CAP_FOWNER in the initial user namespace.
(This is needed to prevent a user from encrypting their data with
another user's key.) The key must remain added while
FS_IOC_SET_ENCRYPTION_POLICY is executing. However, if the new
encrypted directory does not need to be accessed immediately, then the
key can be removed right away afterwards.
Note that the ext4 filesystem does not allow the root directory to be
encrypted, even if it is empty. Users who want to encrypt an entire
filesystem 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 the
process have the CAP_FOWNER capability in a namespace with the file
owner's uid mapped
- ``EEXIST``: the file is already encrypted with an encryption policy
different from the one specified
- ``EINVAL``: an invalid encryption policy was specified (invalid
version, mode(s), or flags; or reserved bits were set); or a v1
encryption policy was specified but the directory has the casefold
flag enabled (casefolding is incompatible with v1 policies).
- ``ENOKEY``: a v2 encryption policy was specified, but the key with
the specified ``master_key_identifier`` has not been added, nor does
the process have the CAP_FOWNER capability in the initial user
namespace
- ``ENOTDIR``: the file is unencrypted and is a regular file, not a
directory
- ``ENOTEMPTY``: the file is unencrypted and is a nonempty directory
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for filesystems, or the filesystem superblock has not
had encryption enabled on it. (For example, to use encryption on an
ext4 filesystem, CONFIG_FS_ENCRYPTION must be enabled in the
kernel config, and the superblock must have had the "encrypt"
feature flag enabled using ``tune2fs -O encrypt`` or ``mkfs.ext4 -O
encrypt``.)
- ``EPERM``: this directory may not be encrypted, e.g. because it is
the root directory of an ext4 filesystem
- ``EROFS``: the filesystem is readonly
정책 조회, salt와 nonce 조회
743-840정책 조회에는 `FS_IOC_GET_ENCRYPTION_POLICY_EX`를 우선 사용하고 `ENOTTY`일 때만 구형 `FS_IOC_GET_ENCRYPTION_POLICY`로 폴백해야 합니다. 확장 ioctl의 인수는 `policy_size`와 version·v1·v2 union을 가지며, 호출 전 `policy_size`를 union의 수용 크기로 초기화합니다. 성공하면 실제 정책 크기와 버전별 구조체가 반환됩니다.
확장 조회의 `EINVAL`은 알 수 없는 정책 버전, `ENODATA`는 정책 없음, `ENOTTY`는 ioctl 미지원, `EOPNOTSUPP`는 파일시스템 암호화 미지원, `EOVERFLOW`는 제공한 버퍼가 정책보다 작음을 뜻합니다.
디렉터리가 암호화되었는지만 확인하려면 `FS_IOC_GETFLAGS`의 `FS_ENCRYPT_FL` 또는 `statx()`의 `STATX_ATTR_ENCRYPTED`도 사용할 수 있습니다.
구형 `FS_IOC_GET_ENCRYPTION_POLICY`는 v1만 반환합니다. 새 커널에서 v2 정책에 호출하면 `EINVAL`이므로 확장 ioctl을 먼저 시도해야 합니다.
`FS_IOC_GET_ENCRYPTION_PWSALT`는 파일시스템 superblock의 무작위 16바이트 salt를 반환하는 폐기 예정 API입니다. passphrase에서 암호 키를 파생하는 데 사용되었지만 사용자 공간이 자체 salt를 관리하는 것이 권장됩니다.
Linux 5.7부터 `FS_IOC_GET_ENCRYPTION_NONCE`는 암호화 inode의 16바이트 nonce를 반환합니다. 암호화되지 않은 inode에는 `ENODATA`를 반환하며 일반 애플리케이션용이 아니라 fscrypt 테스트용입니다.
선호 순서와 반환값을 비교합니다.
Getting an encryption policy
----------------------------
Two ioctls are available to get a file's encryption policy:
- `FS_IOC_GET_ENCRYPTION_POLICY_EX`_
- `FS_IOC_GET_ENCRYPTION_POLICY`_
The extended (_EX) version of the ioctl is more general and is
recommended to use when possible. However, on older kernels only the
original ioctl is available. Applications should try the extended
version, and if it fails with ENOTTY fall back to the original
version.
FS_IOC_GET_ENCRYPTION_POLICY_EX
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_GET_ENCRYPTION_POLICY_EX ioctl retrieves the encryption
policy, if any, for a directory or regular file. No additional
permissions are required beyond the ability to open the file. It
takes in a pointer to struct fscrypt_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 initialize ``policy_size`` to the size available for
the policy struct, i.e. ``sizeof(arg.policy)``.
On success, the policy struct is returned in ``policy``, and its
actual size is returned in ``policy_size``. ``policy.version`` should
be checked to determine the version of policy returned. Note that the
version 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 unrecognized
encryption policy version
- ``ENODATA``: the file is not encrypted
- ``ENOTTY``: 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 encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it
- ``EOVERFLOW``: the file is encrypted and uses a recognized
encryption policy version, but the policy struct does not fit into
the provided buffer
Note: if you only need to know whether a file is encrypted or not, on
most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl
and check for FS_ENCRYPT_FL, or to use the statx() system call and
check for STATX_ATTR_ENCRYPTED in stx_attributes.
FS_IOC_GET_ENCRYPTION_POLICY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve the
encryption policy, if any, for a directory or regular file. However,
unlike `FS_IOC_GET_ENCRYPTION_POLICY_EX`_,
FS_IOC_GET_ENCRYPTION_POLICY only supports the original policy
version. It takes in a pointer directly to struct fscrypt_policy_v1
rather than struct fscrypt_get_policy_ex_arg.
The error codes for FS_IOC_GET_ENCRYPTION_POLICY are the same as those
for FS_IOC_GET_ENCRYPTION_POLICY_EX, except that
FS_IOC_GET_ENCRYPTION_POLICY also returns ``EINVAL`` if the file is
encrypted using a newer encryption policy version.
Getting the per-filesystem salt
-------------------------------
Some filesystems, such as ext4 and F2FS, also support the deprecated
ioctl FS_IOC_GET_ENCRYPTION_PWSALT. This ioctl retrieves a randomly
generated 16-byte value stored in the filesystem superblock. This
value is intended to used as a salt when deriving an encryption key
from a passphrase or other low-entropy user credential.
FS_IOC_GET_ENCRYPTION_PWSALT is deprecated. Instead, prefer to
generate 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 the
encryption is being done correctly. It is not needed for normal use
of fscrypt.
Master key 추가와 legacy keyring
841-1017새 API에서는 `FS_IOC_ADD_ENCRYPTION_KEY`로 파일시스템별 keyring에 master key를 추가합니다. `struct fscrypt_add_key_arg`는 `key_spec`, `raw_size`, `key_id`, `flags`, reserved 영역, 가변 길이 `raw[]`로 구성됩니다. `key_spec`은 v1용 descriptor 또는 v2용 identifier 형식입니다.
구조체 전체와 reserved 영역은 0으로 초기화해야 합니다. v1 descriptor 형식의 키를 추가하려면 초기 user namespace의 `CAP_SYS_ADMIN`이 필요합니다. v2 identifier는 커널이 raw key의 암호학적 해시로 계산해 출력하므로 권한 없는 사용자도 추가할 수 있지만 keyring quota의 적용을 받습니다.
`key_id`가 0이면 `raw_size`만큼의 키 바이트를 `raw[]`에 직접 넣습니다. `key_id`가 0이 아니면 `raw_size`는 0이어야 하고 Linux keyring의 `fscrypt-provisioning` 키를 참조합니다. 해당 키 payload는 type, flags, raw key size와 바이트를 담고 호출자는 그 키에 Search 권한이 있어야 합니다. 직접 raw key 전달이 보통 더 단순하지만, provisioning key는 재마운트 등에서 키를 다시 공급하는 데 유용합니다.
hardware-wrapped key는 `FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED`를 add 인수와 provisioning payload 양쪽에 필요할 때 모두 설정합니다. wrapped key는 descriptor 형식과 함께 사용할 수 없습니다.
v2 키는 effective UID별 사용자의 claim을 추적합니다. 같은 키를 다른 사용자가 다시 추가하면 키 자체를 중복 저장하지 않고 그 사용자의 claim을 만들며, raw key를 알고 있음을 증명해야 합니다. 이미 자신이 추가한 키를 다시 추가해도 성공 0을 반환합니다.
주요 오류는 provisioning key Search 권한 부족 `EACCES`, payload 형식 오류 `EBADMSG`, keyring quota 초과 `EDQUOT`, 구조체·specifier·크기·flag 오류 `EINVAL`, 제공 키가 기존 identifier와 불일치 `EKEYREJECTED`, provisioning key 부재 `ENOKEY`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 `EOPNOTSUPP`입니다.
v1의 legacy 방식은 process-subscribed keyring에 type `logon`, description `fscrypt:` 뒤에 16자리 소문자 16진 descriptor를 붙여 키를 추가합니다. payload는 최대 64바이트 raw key와 size, mode 0을 담는 구조체입니다. 파일시스템별 prefix도 과거에 사용됐지만 폐기 예정입니다.
legacy keyring 방식은 안전한 remove ioctl이 없고 전역 keyring 상태가 파일시스템별 상태 API와 맞지 않으므로 새 코드에서 사용해서는 안 됩니다. `FS_IOC_ADD_ENCRYPTION_KEY`와 v2 정책을 사용해야 합니다.
직접 키와 provisioning key가 파일시스템 keyring에 합류하는 흐름입니다.
키 공급 경로별 실패 의미입니다.
Adding keys
-----------
FS_IOC_ADD_ENCRYPTION_KEY
~~~~~~~~~~~~~~~~~~~~~~~~~
The FS_IOC_ADD_ENCRYPTION_KEY ioctl adds a master encryption key to
the filesystem, making all files on the filesystem which were
encrypted 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 in
a pointer to struct fscrypt_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 2
struct 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[];
};
struct fscrypt_add_key_arg must be zeroed, then initialized
as follows:
- If the key is being added for use by v1 encryption policies, then
``key_spec.type`` must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, and
``key_spec.u.descriptor`` must contain the descriptor of the key
being added, corresponding to the value in the
``master_key_descriptor`` field of struct fscrypt_policy_v1.
To add this type of key, the calling process must have the
CAP_SYS_ADMIN capability in the initial user namespace.
Alternatively, if the key is being added for use by v2 encryption
policies, then ``key_spec.type`` must contain
FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, and ``key_spec.u.identifier`` is
an *output* field which the kernel fills in with a cryptographic
hash of the key. To add this type of key, the calling process does
not need any privileges. However, the number of keys that can be
added is limited by the user's quota for the keyrings service (see
``Documentation/security/keys/core.rst``).
- ``raw_size`` must be the size of the ``raw`` key provided, in bytes.
Alternatively, if ``key_id`` is nonzero, this field must be 0, since
in that case the size is implied by the specified Linux keyring key.
- ``key_id`` is 0 if the key is given directly in the ``raw`` field.
Otherwise ``key_id`` is the ID of a Linux keyring key of type
"fscrypt-provisioning" whose payload is struct
fscrypt_provisioning_key_payload whose ``raw`` field contains the
key, whose ``type`` field matches ``key_spec.type``, and whose
``flags`` field matches ``flags``. Since ``raw`` is
variable-length, the total size of this key's payload must be
``sizeof(struct fscrypt_provisioning_key_payload)`` plus the number
of key bytes. The process must have Search permission on this key.
Most users should leave this 0 and specify the key directly. The
support for specifying a Linux keyring key is intended mainly to
allow 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 a
hardware-wrapped key. See `Hardware-wrapped keys`_. This flag
can't be used if FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR is used.
- ``raw`` is a variable-length field which must contain the actual
key, ``raw_size`` bytes long. Alternatively, if ``key_id`` is
nonzero, then this field is unused. Note that despite being named
``raw``, if FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED is specified then it
will contain a wrapped key, not a raw key.
For v2 policy keys, the kernel keeps track of which user (identified
by effective user ID) added the key, and only allows the key to be
removed by that user --- or by "root", if they use
`FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_.
However, if another user has added the key, it may be desirable to
prevent that other user from unexpectedly removing it. Therefore,
FS_IOC_ADD_ENCRYPTION_KEY may also be used to add a v2 policy key
*again*, 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 the
current user, rather than actually add the key again (but the key must
still be provided, as a proof of knowledge).
FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim to
the 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 the
caller does not have the CAP_SYS_ADMIN capability in the initial
user namespace; or the key was specified by Linux key ID but the
process lacks Search permission on the key.
- ``EBADMSG``: invalid hardware-wrapped key
- ``EDQUOT``: the key quota for this user would be exceeded by adding
the key
- ``EINVAL``: invalid key size or key specifier type, or reserved bits
were set
- ``EKEYREJECTED``: the key was specified by Linux key ID, but the key
has the wrong type
- ``ENOKEY``: the key was specified by Linux key ID, but no key exists
with that ID
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it; or a hardware wrapped key was specified
but the filesystem does not support inline encryption or the hardware
does not support hardware-wrapped keys
Legacy method
~~~~~~~~~~~~~
For v1 encryption policies, a master encryption key can also be
provided by adding it to a process-subscribed keyring, e.g. to a
session keyring, or to a user keyring if the user keyring is linked
into the session keyring.
This method is deprecated (and not supported for v2 encryption
policies) for several reasons. First, it cannot be used in
combination with FS_IOC_REMOVE_ENCRYPTION_KEY (see `Removing keys`_),
so for removing a key a workaround such as keyctl_unlink() in
combination with ``sync; echo 2 > /proc/sys/vm/drop_caches`` would
have to be used. Second, it doesn't match the fact that the
locked/unlocked status of encrypted files (i.e. whether they appear to
be in plaintext form or in ciphertext form) is global. This mismatch
has caused much confusion as well as real problems when processes
running under different UIDs, such as a ``sudo`` command, need to
access encrypted files.
Nevertheless, to add a key to one of the process-subscribed keyrings,
the add_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 be
read back by userspace. The key description must be "fscrypt:"
followed by the 16-character lower case hex representation of the
``master_key_descriptor`` that was set in the encryption policy. The
key payload must conform to the following structure::
#define FSCRYPT_MAX_KEY_SIZE 64
struct 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 in
``raw`` with ``size`` indicating its size in bytes. That is, the
bytes ``raw[0..size-1]`` (inclusive) are the actual key.
The key description prefix "fscrypt:" may alternatively be replaced
with a filesystem-specific prefix such as "ext4:". However, the
filesystem-specific prefixes are deprecated and should not be used in
new programs.
키 제거, 사용자 claim과 상태 조회
1018-1205`FS_IOC_REMOVE_ENCRYPTION_KEY`와 `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`는 `FS_IOC_ADD_ENCRYPTION_KEY`로 관리되는 파일시스템별 keyring의 키만 제거합니다. v1 descriptor 제거에는 초기 user namespace의 `CAP_SYS_ADMIN`이 필요하고 v2는 identifier를 사용합니다.
일반 REMOVE ioctl은 v2에서 호출자의 claim을 먼저 제거합니다. 여러 사용자가 같은 키를 추가했다면 hard link와 비슷하게 모든 claim이 없어져야 실제 키가 제거됩니다. 마지막 claim이 사라지면 커널은 키를 지우고 잠금 해제 inode를 퇴거하려 합니다.
키가 실제로 지워져도 사용 중 inode의 per-file key는 남을 수 있습니다. 반환 구조체의 `FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY`는 이러한 파일이 남았음을 뜻하며 파일을 닫은 뒤 ioctl을 재시도해야 합니다. `FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS`는 다른 사용자의 claim 때문에 키가 남았음을 뜻합니다.
`FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`는 모든 사용자 claim과 키를 한 번에 제거하며 초기 user namespace의 `CAP_SYS_ADMIN`이 필요합니다. 권한이 없으면 `EACCES`입니다.
제거 ioctl의 오류는 접근 권한 부족 `EACCES`, 구조체·specifier·reserved 오류 `EINVAL`, 자신이 claim하지 않았거나 키가 없음 `ENOKEY`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 `EOPNOTSUPP`입니다. 성공 0만으로 완전 제거를 단정하지 말고 반환 status flags를 반드시 확인해야 합니다.
`FS_IOC_GET_ENCRYPTION_KEY_STATUS`는 `FSCRYPT_KEY_STATUS_ABSENT`, `PRESENT`, `INCOMPLETELY_REMOVED` 중 하나를 반환합니다. `PRESENT`는 키가 있고 사용할 수 있음을, `INCOMPLETELY_REMOVED`는 master key는 제거됐지만 사용 중 파일 때문에 일부 per-file key가 남았음을 뜻합니다.
v2에서는 `FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF`로 현재 effective UID가 claim을 보유하는지 알 수 있고 `user_count`로 전체 claim 수를 확인합니다. v1에는 이 정보가 없습니다. 이 API는 암호화 디렉터리의 키가 없는지 확인한 뒤 passphrase를 묻는 용도에 유용합니다.
상태 조회는 파일시스템별 keyring만 보며 legacy process-subscribed keyring에만 추가된 v1 키는 볼 수 없습니다. 상태 조회 오류는 인수 오류 `EINVAL`, ioctl 미지원 `ENOTTY`, 파일시스템 암호화 미지원 또는 superblock에서 암호화가 켜지지 않은 `EOPNOTSUPP`입니다.
여러 사용자가 같은 키를 추가했을 때 실제 제거 조건입니다.
status와 removal flag를 함께 해석해야 합니다.
Removing keys
-------------
Two ioctls are available for removing a key that was added by
`FS_IOC_ADD_ENCRYPTION_KEY`_:
- `FS_IOC_REMOVE_ENCRYPTION_KEY`_
- `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS`_
These two ioctls differ only in cases where v2 policy keys are added
or removed by non-root users.
These ioctls don't work on keys that were added via the legacy
process-subscribed keyrings mechanism.
Before using these ioctls, read the `Online attacks`_ section for a
discussion 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 master
encryption key from the filesystem, and possibly removes the key
itself. It can be executed on any file or directory on the target
filesystem, but using the filesystem's root directory is recommended.
It takes in a pointer to struct fscrypt_remove_key_arg, defined
as 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 fill
in ``key_spec.u.descriptor``. To remove this type of key, the
calling process must have the CAP_SYS_ADMIN capability in the
initial user namespace.
- To remove a key used by v2 encryption policies, set
``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
in ``key_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's
claim 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, and
FS_IOC_REMOVE_ENCRYPTION_KEY will only succeed as uid 1000. Or, if
both uids 1000 and 2000 added the key, then for each uid
FS_IOC_REMOVE_ENCRYPTION_KEY will only remove their own claim. Only
once *both* are removed is the key really removed. (Think of it like
unlinking a file that may have hard links.)
If FS_IOC_REMOVE_ENCRYPTION_KEY really removes the key, it will also
try to "lock" all files that had been unlocked with the key. It won't
lock files that are still in-use, so this ioctl is expected to be used
in cooperation with userspace ensuring that none of the files are
still open. However, if necessary, this ioctl can be executed again
later 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 to
the key was removed, or the key was already removed but had files
remaining to be the locked so the ioctl retried locking them. In any
of these cases, ``removal_status_flags`` is filled in with the
following 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 only
the user's claim to the key was removed.
- ``FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS``: set if only the
user'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 type
was specified, but the caller does not have the CAP_SYS_ADMIN
capability in the initial user namespace
- ``EINVAL``: invalid key specifier type, or reserved bits were set
- ``ENOKEY``: the key object was not found at all, i.e. it was never
added in the first place or was already fully removed including all
files locked; or, the user does not have a claim to the key (but
someone else does).
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same as
`FS_IOC_REMOVE_ENCRYPTION_KEY`_, except that for v2 policy keys, the
ALL_USERS version of the ioctl will remove all users' claims to the
key, not just the current user's. I.e., the key itself will always be
removed, no matter how many users have added it. This difference is
only 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 user
namespace. 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 a
master encryption key. It can be executed on any file or directory on
the target filesystem, but using the filesystem's root directory is
recommended. It takes in a pointer to
struct fscrypt_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 in ``key_spec``:
- To get the status of a key for v1 encryption policies, set
``key_spec.type`` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
in ``key_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 fill
in ``key_spec.u.identifier``.
On success, 0 is returned and the kernel fills in the output fields:
- ``status`` indicates whether the key is absent, present, or
incompletely removed. Incompletely removed means that removal has
been initiated, but some files are still in use; i.e.,
`FS_IOC_REMOVE_ENCRYPTION_KEY`_ returned 0 but set the informational
status 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 key
has added by the current user. This is only set for keys
identified by ``identifier`` rather than by ``descriptor``.
- ``user_count`` specifies the number of users who have added the key.
This is only set for keys identified by ``identifier`` rather than
by ``descriptor``.
FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:
- ``EINVAL``: invalid key specifier type, or reserved bits were set
- ``ENOTTY``: this type of filesystem does not implement encryption
- ``EOPNOTSUPP``: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it
Among other use cases, FS_IOC_GET_ENCRYPTION_KEY_STATUS can be useful
for determining whether the key for a given encrypted directory needs
to be added before prompting the user for the passphrase needed to
derive the key.
FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys in
the filesystem-level keyring, i.e. the keyring managed by
`FS_IOC_ADD_ENCRYPTION_KEY`_ and `FS_IOC_REMOVE_ENCRYPTION_KEY`_. It
cannot get the status of a key that has only been added for use by v1
encryption policies using the legacy mechanism involving
process-subscribed keyrings.
키 유무에 따른 접근 의미와 정책 강제
1206-1319키가 있으면 암호화 일반 파일, 디렉터리, 심볼릭 링크는 대부분 평문 객체처럼 동작합니다. 다만 암호화되지 않았거나 키·모드·flag가 다른 정책의 파일을 암호화 디렉터리로 rename하거나 link할 수 없고 `EXDEV`가 납니다. 같은 암호화 디렉터리 안이나 암호화 디렉터리에서 평문 디렉터리로 이동하는 것은 가능합니다.
`mv`가 평문 파일을 암호화 디렉터리로 옮길 때는 사용자 공간에서 복사 후 삭제로 구현됩니다. 원래 평문 데이터가 디스크 여유 공간에 남을 수 있으므로 처음부터 암호화 상태로 파일을 만드는 편이 안전합니다. `shred`도 모든 파일시스템과 저장장치에서 효과가 보장되지 않습니다.
암호화 파일의 direct I/O는 특정 조건에서만 지원합니다. `FALLOC_FL_COLLAPSE_RANGE`, `FALLOC_FL_INSERT_RANGE`, ext4 `EXT4_IOC_MOVE_EXT`, F2FS `F2FS_IOC_MOVE_RANGE`는 `EOPNOTSUPP`입니다. ext4 data journaling은 암호화 일반 파일에서 지원되지 않아 ordered data mode로 폴백합니다. DAX도 지원하지 않습니다.
암호화 심볼릭 링크의 최대 길이는 평문보다 2바이트 짧습니다. 예를 들어 4K 블록 ext4에서 종료 NUL을 제외한 평문 링크는 4095바이트, 암호화 링크는 4093바이트입니다. `mmap`은 페이지 캐시에 암호문이 아니라 평문을 보관하므로 지원됩니다.
키가 없어도 `stat()`으로 메타데이터를 읽고 디렉터리를 나열하며 파일을 삭제할 수 있습니다. 파일 이름은 암호문에서 파생한 인코딩 형태로 보이고 `NAME_MAX` 이내이며 `/`와 NUL을 포함하지 않고 각 directory entry를 고유하게 식별합니다. `.`과 `..`는 항상 평문입니다. `unlink()`, 빈 디렉터리 `rmdir()`, `rm -r`도 동작합니다.
키 없이 심볼릭 링크 대상을 읽거나 따라갈 수는 있지만 암호화 표현으로 보이므로 유용한 위치를 가리킬 가능성은 낮습니다. 일반 파일 open·truncate는 `ENOKEY`이며 fd가 필요한 `read()`, `write()`, `mmap()`, `fallocate()`, `ioctl()`도 불가능합니다.
키가 없으면 암호화 디렉터리 안에 어떤 형식의 파일도 만들거나 link할 수 없고, 그 안의 이름을 rename의 source 또는 target으로 쓸 수 없으며 `O_TMPFILE`도 만들 수 없습니다. 모두 `ENOKEY`입니다. 키 없이 암호화 파일을 백업·복원하는 전용 API는 아직 구현되지 않았습니다.
정책을 설정한 디렉터리에서 새로 만들어지는 일반 파일, 디렉터리, 심볼릭 링크는 재귀적으로 정책을 상속합니다. named pipe, device node, UNIX domain socket 같은 특수 파일은 암호화하지 않습니다.
특수 파일을 제외하면 평문 파일이나 다른 정책의 파일이 암호화 트리에 들어가는 것을 금지하고 link·rename에 `EXDEV`를 반환합니다. `->lookup()`에서도 이를 검사해 공격자가 오프라인으로 알려진 위치의 암호화를 비활성화하거나 낮춘 뒤 애플리케이션이 민감 데이터를 쓰게 하는 공격을 제한합니다. verified boot 시스템은 접근 전에 최상위 암호화 정책을 검증해야 합니다.
같은 inode가 key state에 따라 제공하는 인터페이스입니다.
Access semantics
================
With the key
------------
With the encryption key, encrypted regular files, directories, and
symlinks 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 encryption
policy (i.e. different key, modes, or flags), cannot be renamed or
linked into an encrypted directory; see `Encryption policy
enforcement`_. Attempts to do so will fail with EXDEV. However,
encrypted files can be renamed within an encrypted directory, or
into an unencrypted directory.
Note: "moving" an unencrypted file into an encrypted directory, e.g.
with the `mv` program, is implemented in userspace by a copy
followed by a delete. Be aware that the original unencrypted data
may remain recoverable from free space on the disk; prefer to keep
all files encrypted from the very beginning. The `shred` program
may be used to overwrite the source files but isn't guaranteed to be
effective on all filesystems and storage devices.
- Direct I/O is supported on encrypted files only under some
circumstances. For details, see `Direct I/O support`_.
- The fallocate operations FALLOC_FL_COLLAPSE_RANGE and
FALLOC_FL_INSERT_RANGE are not supported on encrypted files and will
fail with EOPNOTSUPP.
- Online defragmentation of encrypted files is not supported. The
EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
EOPNOTSUPP.
- The ext4 filesystem does not support data journaling with encrypted
regular 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 than
the maximum length of an unencrypted symlink. For example, on an
EXT4 filesystem with a 4K block size, unencrypted symlinks can be up
to 4095 bytes long, while encrypted symlinks can only be up to 4093
bytes long (both lengths excluding the terminating null).
Note that mmap *is* supported. This is possible because the pagecache
for an encrypted file contains the plaintext, not the ciphertext.
Without the key
---------------
Some filesystem operations may be performed on encrypted regular
files, directories, and symlinks even before their encryption key has
been 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 be
listed in an encoded form derived from their ciphertext. The
current encoding algorithm is described in `Filename hashing and
encoding`_. The algorithm is subject to change, but it is
guaranteed that the presented filenames will be no longer than
NAME_MAX bytes, will not contain the ``/`` or ``\0`` characters, and
will uniquely identify directory entries.
The ``.`` and ``..`` directory entries are special. They are always
present and are not encrypted or encoded.
- Files may be deleted. That is, nondirectory files may be deleted
with unlink() as usual, and empty directories may be deleted with
rmdir() as usual. Therefore, ``rm`` and ``rm -r`` will work as
expected.
- Symlink targets may be read and followed, but they will be presented
in encrypted form, similar to filenames in directories. Hence, they
are 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 any
regular file operations that require a file descriptor, such as
read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.
Also without the key, files of any type (including directories) cannot
be created or linked into an encrypted directory, nor can a name in an
encrypted directory be the source or target of a rename, nor can an
O_TMPFILE temporary file be created in an encrypted directory. All
such operations will fail with ENOKEY.
It is not currently possible to backup and restore encrypted files
without the encryption key. This would require special APIs which
have not yet been implemented.
Encryption policy enforcement
=============================
After an encryption policy has been set on a directory, all regular
files, 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 --- will
not be encrypted.
Except for those special files, it is forbidden to have unencrypted
files, or files encrypted with a different encryption policy, in an
encrypted directory tree. Attempts to link or rename such a file into
an encrypted directory will fail with EXDEV. This is also enforced
during ->lookup() to provide limited protection against offline
attacks that try to disable or downgrade encryption in known locations
where applications may later write sensitive data. It is recommended
that systems implementing a form of "verified boot" take advantage of
this by validating all top-level encryption policies prior to access.
인라인 암호화, hardware-wrapped key와 direct I/O
1320-1445최신 모바일 SoC 등의 inline encryption hardware는 저장장치로 오가는 동안 데이터를 암복호화합니다. Linux의 block layer 확장인 blk-crypto는 filesystem이 bio에 encryption context를 붙이게 합니다. 자세한 내용은 `Documentation/block/inline-encryption.rst`의 `inline_encryption` 절에 있습니다.
현재 ext4와 F2FS에서 fscrypt는 파일 내용에 Crypto API 대신 blk-crypto를 사용할 수 있습니다. 커널에서 `CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y`를 설정하고 파일시스템을 `inlinecrypt` 옵션으로 마운트합니다.
`inlinecrypt`는 가능할 때 인라인 암호화를 사용하라는 뜻이지 강제하지는 않습니다. 하드웨어가 필요한 알고리즘·data unit size를 지원하지 않고 blk-crypto fallback도 사용할 수 없으면 Crypto API로 폴백합니다. blk-crypto fallback에는 `CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y`가 필요하고 파일은 hardware-wrapped key가 아닌 raw key로 보호되어야 합니다.
이 문서가 설명하는 현재 구현에서 fscrypt는 항상 보통 4096바이트인 파일시스템 블록 크기를 data unit size로 쓰므로 그 크기를 지원하는 하드웨어만 사용할 수 있습니다. 인라인 사용 여부는 암호문이나 on-disk format을 바꾸지 않으므로 자유롭게 전환할 수 있습니다. 단, hardware-wrapped key 파일은 하드웨어만 암복호화할 수 있어 `inlinecrypt` 마운트에서만 접근할 수 있습니다.
hardware-wrapped key는 커널 메모리에 래핑된 암호문 형태로만 존재하고 인라인 하드웨어만 풀 수 있으며 현재 부팅에 시간적으로 결속됩니다. 커널 메모리가 유출되어도 키를 보호하고 키 개수를 제한하지 않으면서, 파일 이름 암호화처럼 같은 키에 연계되지만 인라인 하드웨어로 처리할 수 없는 작업도 지원합니다. 이는 fscrypt 전용이 아니라 blk-crypto 기능입니다.
`FS_IOC_ADD_ENCRYPTION_KEY`로 hardware-wrapped key를 추가할 때 `struct fscrypt_add_key_arg.flags`와 provisioning key를 쓴다면 `struct fscrypt_provisioning_key_payload.flags` 모두에 `FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED`를 지정합니다. 키는 장기 래핑 형태가 아니라 ephemeral-wrapped 형태여야 합니다.
wrapped key 파일은 시스템의 인라인 하드웨어에 묶이므로 portable filesystem image에 넣을 수 없습니다. 현재는 master key마다 내용 키 하나만 있다고 가정하는 `IV_INO_LBLK_64`와 `IV_INO_LBLK_32` 정책만 호환됩니다. 향후 per-file nonce를 storage stack으로 전달해 하드웨어가 per-file key를 파생하도록 개선할 수 있습니다.
내용 I/O에서 fscrypt는 wrapped key를 bio crypt context에 붙입니다. block layer가 keyslot을 프로그래밍할 때 하드웨어는 입력 키를 직접 넣지 않고 ephemeral wrapping key로 풀어 inline encryption key를 파생합니다. 실제 keyslot에는 이 파생 키가 들어가며 소프트웨어에는 절대 노출되지 않습니다.
파일 이름 키, key identifier, dirhash key 같은 다른 하위 키에는 raw key material이 필요합니다. fscrypt는 하드웨어에 wrapped key로부터 암호학적으로 격리된 `software secret`을 파생해 달라고 요청하고, 이를 KDF 키로 삼아 내용 키 외 하위 키를 파생합니다. 따라서 wrapped 기능이 보호하는 것은 파일 내용 암호화 키이며 파일 이름 키 등은 보호하지 않습니다.
암호화 파일의 direct I/O에는 인라인 암호화가 필요합니다. 보통 `-o inlinecrypt`와 하드웨어가 필요하지만 소프트웨어 fallback도 가능합니다. 또한 파일 위치, 모든 I/O segment 길이, 모든 buffer 메모리 주소가 파일시스템 블록 크기의 배수여야 합니다. 파일시스템 블록은 장치 logical block보다 클 수 있습니다. 조건 하나라도 맞지 않으면 buffered I/O로 폴백합니다.
소프트웨어에 노출되는 정보와 하드웨어에만 존재하는 키를 분리합니다.
평문 파일의 일반 조건에 더해 모두 만족해야 합니다.
Inline encryption support
=========================
Many newer systems (especially mobile SoCs) have *inline encryption
hardware* that can encrypt/decrypt data while it is on its way to/from
the storage device. Linux supports inline encryption through a set of
extensions to the block layer called *blk-crypto*. blk-crypto allows
filesystems to attach encryption contexts to bios (I/O requests) to
specify how the data will be encrypted or decrypted in-line. For more
information about blk-crypto, see
:ref:`Documentation/block/inline-encryption.rst <inline_encryption>`.
On supported filesystems (currently ext4 and f2fs), fscrypt can use
blk-crypto instead of the kernel crypto API to encrypt/decrypt file
contents. To enable this, set CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y in
the kernel configuration, and specify the "inlinecrypt" mount option
when mounting the filesystem.
Note that the "inlinecrypt" mount option just specifies to use inline
encryption when possible; it doesn't force its use. fscrypt will
still fall back to using the kernel crypto API on files where the
inline 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-fallback
to be usable, it must be enabled in the kernel configuration with
CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y, and the file must be
protected by a raw key rather than a hardware-wrapped key.)
Currently fscrypt always uses the filesystem block size (which is
usually 4096 bytes) as the data unit size. Therefore, it can only use
inline encryption hardware that supports that data unit size.
Inline encryption doesn't affect the ciphertext or other aspects of
the on-disk format, so users may freely switch back and forth between
using "inlinecrypt" and not using "inlinecrypt". An exception is that
files that are protected by a hardware-wrapped key can only be
encrypted/decrypted by the inline encryption hardware and therefore
can only be accessed when the "inlinecrypt" mount option is used. For
more information about hardware-wrapped keys, see below.
Hardware-wrapped keys
---------------------
fscrypt supports using *hardware-wrapped keys* when the inline
encryption hardware supports it. Such keys are only present in kernel
memory in wrapped (encrypted) form; they can only be unwrapped
(decrypted) by the inline encryption hardware and are temporally bound
to the current boot. This prevents the keys from being compromised if
kernel memory is leaked. This is done without limiting the number of
keys that can be used and while still allowing the execution of
cryptographic tasks that are tied to the same key but can't use inline
encryption hardware, e.g. filenames encryption.
Note that hardware-wrapped keys aren't specific to fscrypt; they are a
block layer feature (part of *blk-crypto*). For more details about
hardware-wrapped keys, see the block layer documentation at
:ref:`Documentation/block/inline-encryption.rst
<hardware_wrapped_keys>`. The rest of this section just focuses on
the details of how fscrypt can use hardware-wrapped keys.
fscrypt supports hardware-wrapped keys by allowing the fscrypt master
keys to be hardware-wrapped keys as an alternative to raw keys. To
add a hardware-wrapped key with `FS_IOC_ADD_ENCRYPTION_KEY`_,
userspace must specify FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED in the
``flags`` field of struct fscrypt_add_key_arg and also in the
``flags`` field of struct fscrypt_provisioning_key_payload when
applicable. The key must be in ephemerally-wrapped form, not
long-term wrapped form.
Some limitations apply. First, files protected by a hardware-wrapped
key are tied to the system's inline encryption hardware. Therefore
they 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 with
`IV_INO_LBLK_64 policies`_ and `IV_INO_LBLK_32 policies`_, as it
assumes that there is just one file contents encryption key per
fscrypt master key rather than one per file. Future work may address
this limitation by passing per-file nonces down the storage stack to
allow the hardware to derive per-file keys.
Implementation-wise, to encrypt/decrypt the contents of files that are
protected by a hardware-wrapped key, fscrypt uses blk-crypto,
attaching the hardware-wrapped key to the bio crypt contexts. As is
the case with raw keys, the block layer will program the key into a
keyslot when it isn't already in one. However, when programming a
hardware-wrapped key, the hardware doesn't program the given key
directly into a keyslot but rather unwraps it (using the hardware's
ephemeral wrapping key) and derives the inline encryption key from it.
The inline encryption key is the key that actually gets programmed
into a keyslot, and it is never exposed to software.
However, fscrypt doesn't just do file contents encryption; it also
uses its master keys to derive filenames encryption keys, key
identifiers, and sometimes some more obscure types of subkeys such as
dirhash keys. So even with file contents encryption out of the
picture, fscrypt still needs a raw key to work with. To get such a
key from a hardware-wrapped key, fscrypt asks the inline encryption
hardware to derive a cryptographically isolated "software secret" from
the hardware-wrapped key. fscrypt uses this "software secret" to key
its KDF to derive all subkeys other than file contents keys.
Note that this implies that the hardware-wrapped key feature only
protects the file contents encryption keys. It doesn't protect other
fscrypt subkeys such as filenames encryption keys.
Direct I/O support
==================
For direct I/O on an encrypted file to work, the following conditions
must be met (in addition to the conditions for direct I/O on an
unencrypted file):
* The file must be using inline encryption. Usually this means that
the filesystem must be mounted with ``-o inlinecrypt`` and inline
encryption hardware must be present. However, a software fallback
is also available. For details, see `Inline 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 lengths
of all I/O segments, and the memory addresses of all I/O buffers
must be multiples of this value. Note that the filesystem block
size 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 the
encrypted file will fall back to buffered I/O.
On-disk context, 데이터 경로와 이름 인코딩
1446-1556암호화 정책의 on-disk 표현은 `struct fscrypt_context_v1` 또는 `struct fscrypt_context_v2`입니다. 저장 위치는 파일시스템이 정하지만 보통 숨은 확장 속성입니다. 암호화 xattr에는 특별한 의미가 있으므로 `getxattr()`·`setxattr()` 같은 일반 xattr system call에 노출하면 안 됩니다. 빈 디렉터리가 아닌 객체에 정책이 임의로 추가·제거되는 혼란을 막기 위해서입니다.
context 구조체는 대응하는 policy 구조체와 같은 정보를 담고 16바이트 nonce를 추가합니다. nonce는 커널이 무작위로 생성하며 KDF 입력 또는 파일마다 다른 암호문을 만들기 위한 tweak로 사용합니다.
#define FSCRYPT_FILE_NONCE_SIZE 16
struct 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];
};
struct 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];
};
인라인 암호화를 쓸 때 파일시스템은 bio에 encryption context를 연결해 block layer나 하드웨어가 파일 내용을 암복호화하도록 지정하면 됩니다.
인라인을 쓰지 않는 일반 파일 read 경로 `->read_folio()`에서는 암호문을 page cache로 읽고 제자리 복호화할 수 있습니다. 복호화가 끝나기 전에 folio가 사용자 공간에 보이지 않도록 folio lock을 끝까지 유지해야 합니다.
write 경로 `->writepages()`에서는 cache의 평문을 보존해야 하므로 page cache에서 제자리 암호화할 수 없습니다. 임시 buffer 또는 bounce page에 암호화해 그 버퍼를 기록합니다. UBIFS는 암호화와 무관하게 임시 버퍼를 쓰지만 ext4와 F2FS는 암호화를 위해 bounce page를 별도로 할당합니다.
현대 파일시스템의 indexed directory는 파일 이름 해시를 key로 한 트리입니다. 키가 없는 상태에서도 효율적으로 조회해야 하므로 평문 이름이 아니라 directory entry에 실제 저장된 암호문 이름을 해시합니다. 키가 있을 때 `->lookup()`은 사용자가 준 이름을 암호화해 암호문을 얻고 조회합니다. 이 설계는 fsck가 암호화 디렉터리를 최적화하는 것도 가능하게 합니다.
키가 없을 때 raw ciphertext에는 파일 이름에서 금지된 NUL과 `/`가 들어갈 수 있으므로 `readdir()`은 base64url로 인코딩합니다. 보통 `->lookup()`은 이를 디코딩해 원래 암호문으로 되돌립니다.
매우 긴 이름은 base64url 인코딩하면 `NAME_MAX`를 넘으므로 강한 암호문 hash와 디렉터리 조회에 필요한 선택적 파일시스템별 hash를 담은 축약 형식으로 표시합니다. `struct fscrypt_nokey_name`에 세부 구조가 있습니다. `readdir()`로 본 이름을 `->lookup()`이 높은 확률로 같은 entry에 매핑할 수 있게 합니다.
키 없는 상태의 파일 이름 표현은 향후 바뀔 수 있습니다. 영구 백업 형식이 아니라 `rm -r` 같은 명령이 암호화 디렉터리에서도 동작하도록 일시적으로 유효한 이름을 제시하는 수단입니다.
page cache 평문 보존 요구가 읽기와 쓰기 경로를 다르게 만듭니다.
불법 바이트와 NAME_MAX를 피하면서 entry를 다시 찾는 경로입니다.
Implementation details
======================
Encryption context
------------------
An encryption policy is represented on-disk by
struct fscrypt_context_v1 or struct fscrypt_context_v2. It is up to
individual filesystems to decide where to store it, but normally it
would be stored in a hidden extended attribute. It should *not* be
exposed by the xattr-related system calls such as getxattr() and
setxattr() because of the special semantics of the encryption xattr.
(In particular, there would be much confusion if an encryption policy
were to be added to or removed from anything other than an empty
directory.) These structs are defined as follows::
#define FSCRYPT_FILE_NONCE_SIZE 16
#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8
struct 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 16
struct 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 corresponding
policy structs (see `Setting an encryption policy`_), except that the
context structs also contain a nonce. The nonce is randomly generated
by the kernel and is used as KDF input or as a tweak to cause
different files to be encrypted differently; see `Per-file encryption
keys`_ and `DIRECT_KEY policies`_.
Data path changes
-----------------
When inline encryption is used, filesystems just need to associate
encryption contexts with bios to specify how the block layer or the
inline encryption hardware will encrypt/decrypt the file contents.
When inline encryption isn't used, filesystems must encrypt/decrypt
the file contents themselves, as described below:
For the read path (->read_folio()) of regular files, filesystems can
read the ciphertext into the page cache and decrypt it in-place. The
folio lock must be held until decryption has finished, to prevent the
folio from becoming visible to userspace prematurely.
For the write path (->writepages()) of regular files, filesystems
cannot encrypt data in-place in the page cache, since the cached
plaintext must be preserved. Instead, filesystems must encrypt into a
temporary buffer or "bounce page", then write out the temporary
buffer. Some filesystems, such as UBIFS, already use temporary
buffers regardless of encryption. Other filesystems, such as ext4 and
F2FS, have to allocate bounce pages specially for encryption.
Filename hashing and encoding
-----------------------------
Modern filesystems accelerate directory lookups by using indexed
directories. An indexed directory is organized as a tree keyed by
filename hashes. When a ->lookup() is requested, the filesystem
normally hashes the filename being looked up so that it can quickly
find the corresponding directory entry, if any.
With encryption, lookups must be supported and efficient both with and
without the encryption key. Clearly, it would not work to hash the
plaintext filenames, since the plaintext filenames are unavailable
without the key. (Hashing the plaintext filenames would also make it
impossible for the filesystem's fsck tool to optimize encrypted
directories.) Instead, filesystems hash the ciphertext filenames,
i.e. the bytes actually stored on-disk in the directory entries. When
asked to do a ->lookup() with the key, the filesystem just encrypts
the user-supplied name to get the ciphertext.
Lookups without the key are more complicated. The raw ciphertext may
contain the ``\0`` and ``/`` characters, which are illegal in
filenames. Therefore, readdir() must base64url-encode the ciphertext
for presentation. For most filenames, this works fine; on ->lookup(),
the filesystem just base64url-decodes the user-supplied name to get
back to the raw ciphertext.
However, for very long filenames, base64url encoding would cause the
filename length to exceed NAME_MAX. To prevent this, readdir()
actually presents long filenames in an abbreviated form which encodes
a strong "hash" of the ciphertext filename, along with the optional
filesystem-specific hash(es) needed for directory lookups. This
allows the filesystem to still, with a high degree of confidence, map
the filename given in ->lookup() back to a particular directory entry
that was previously listed by readdir(). See
struct fscrypt_nokey_name in the source for more details.
Note that the precise way that filenames are presented to userspace
without the key is subject to change in the future. It is only meant
as a way to temporarily present valid filenames so that commands like
``rm -r`` work as expected on encrypted directories.
xfstests를 이용한 검증
1557-1599fscrypt 검증에는 Linux 파일시스템의 사실상 표준 테스트 스위트인 xfstests를 사용합니다. 먼저 대상 파일시스템에서 `encrypt` 그룹 전체를 실행하고 `inlinecrypt` 마운트 옵션을 추가한 실행으로 인라인 구현도 검사합니다.
kvm-xfstests -c ext4,f2fs -g encrypt
kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
kvm-xfstests -c ubifs -g encrypt
UBIFS도 같은 방식으로 테스트할 수 있지만 emulated UBI volume 준비에 시간이 걸리므로 별도 명령으로 실행합니다. 실패하는 테스트가 없어야 합니다. 다만 generic/549와 generic/550처럼 비기본 암호화 모드를 쓰는 테스트는 필요한 알고리즘이 커널 Crypto API에 빌드되지 않았으면 skip됩니다.
raw block device에 접근하는 generic/399, generic/548, generic/549, generic/550은 UBIFS에서 skip됩니다. 이는 지원되지 않는 테스트 환경 조건에 따른 skip이며 실패와 구분해야 합니다.
ext4와 F2FS에서는 `test_dummy_encryption` 마운트 옵션으로 대부분의 xfstests를 실행할 수도 있습니다. API 호출 없이 모든 새 파일을 dummy key로 자동 암호화해 encrypted I/O path를 더 폭넓게 검사합니다.
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
`-g auto`는 `-g encrypt`보다 훨씬 많은 테스트를 실행해 오래 걸리므로 필요하면 kvm-xfstests 대신 gce-xfstests를 사용할 수 있습니다. raw key·인라인·비기본 모드·UBIFS의 환경 차이를 고려해 skip 이유를 확인하되 실제 실패는 허용하지 않습니다.
파일시스템과 경로별 권장 실행 및 예상 skip입니다.
Tests
=====
To test fscrypt, use xfstests, which is Linux's de facto standard
filesystem test suite. First, run all the tests in the "encrypt"
group on the relevant filesystem(s). One can also run the tests
with the 'inlinecrypt' mount option to test the implementation for
inline encryption support. For example, to test ext4 and
f2fs encryption using `kvm-xfstests
<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>`_::
kvm-xfstests -c ext4,f2fs -g encrypt
kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
UBIFS encryption can also be tested this way, but it should be done in
a separate command, and it takes some time for kvm-xfstests to set up
emulated UBI volumes::
kvm-xfstests -c ubifs -g encrypt
No tests should fail. However, tests that use non-default encryption
modes (e.g. generic/549 and generic/550) will be skipped if the needed
algorithms were not built into the kernel's crypto API. Also, tests
that 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 also
possible to run most xfstests with the "test_dummy_encryption" mount
option. This option causes all new files to be automatically
encrypted with a dummy key, without having to make any API calls.
This tests the encrypted I/O paths more thoroughly. To do this with
kvm-xfstests, use the "encrypt" filesystem configuration::
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
Because this runs many more tests than "-g encrypt" does, it takes
much longer to run; so also consider using `gce-xfstests
<https://github.com/tytso/xfstests-bld/blob/master/Documentation/gce-xfstests.md>`_
instead of kvm-xfstests::
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
요약·해설
fscrypt.rst:1-1599fscrypt는 ext4, F2FS, UBIFS, CephFS에 통합되는 파일시스템 수준 암호화 계층입니다. 디렉터리 트리별 master key와 정책을 사용해 파일 내용과 파일 이름을 보호하고, 파일 크기·권한·시간 같은 비이름 메타데이터는 보호 범위 밖에 둡니다.
새 배포에서는 v2 정책, 강한 무작위 master key, AES-256-XTS/AES-256-CBC-CTS 또는 HCTR2 조합을 기본으로 검토해야 합니다. AES 가속이 없는 장치는 Adiantum이 적합합니다. 키 제거는 열린 파일, 사용자 공간 복사본, VFS 잔여 메모리까지 자동으로 해결하지 않으므로 운영 절차가 암호화 알고리즘만큼 중요합니다.
API 사용자는 정책 구조체의 reserved 필드를 0으로 초기화하고, ADD·REMOVE·STATUS ioctl의 claim 모델과 반환 status flags를 정확히 처리해야 합니다. hardware-wrapped key는 내용 키의 커널 메모리 노출을 줄이지만 인라인 하드웨어와 IV_INO_LBLK 정책에 종속되며 파일 이름 하위 키까지 보호하지는 않습니다.
정책 생성부터 잠금·제거·검증까지의 핵심 흐름입니다.