__  __    __   __  _____      _            _          _____ _          _ _ 
 |  \/  |   \ \ / / |  __ \    (_)          | |        / ____| |        | | |
 | \  / |_ __\ V /  | |__) | __ ___   ____ _| |_ ___  | (___ | |__   ___| | |
 | |\/| | '__|> <   |  ___/ '__| \ \ / / _` | __/ _ \  \___ \| '_ \ / _ \ | |
 | |  | | |_ / . \  | |   | |  | |\ V / (_| | ||  __/  ____) | | | |  __/ | |
 |_|  |_|_(_)_/ \_\ |_|   |_|  |_| \_/ \__,_|\__\___| |_____/|_| |_|\___V 2.1
 if you need WebShell for Seo everyday contact me on Telegram
 Telegram Address : @jackleet
        
        
For_More_Tools: Telegram: @jackleet | Bulk Smtp support mail sender | Business Mail Collector | Mail Bouncer All Mail | Bulk Office Mail Validator | Html Letter private



Upload:

Command:

www-data@216.73.216.186: ~ $
<!DOCTYPE html>

<html lang="en" data-content_root="../">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Filesystem-level encryption (fscrypt) &#8212; The Linux Kernel  documentation</title>
    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=fa44fd50" />
    <link rel="stylesheet" type="text/css" href="../_static/alabaster.css?v=3918102e" />
    <script src="../_static/documentation_options.js?v=5929fcd5"></script>
    <script src="../_static/doctools.js?v=9bcbadda"></script>
    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="fs-verity: read-only file-based authenticity protection" href="fsverity.html" />
    <link rel="prev" title="The Linux Journalling API" href="journalling.html" />
   
  <link rel="stylesheet" href="../_static/custom.css" type="text/css" />
  

  
  

  </head><body>
  <div class="document">
    
      <div class="sphinxsidebar" role="navigation" aria-label="Main">
        <div class="sphinxsidebarwrapper">
            <p class="logo"><a href="../index.html">
              <img class="logo" src="../_static/logo.svg" alt="Logo of The Linux Kernel"/>
            </a></p>
<h1 class="logo"><a href="../index.html">The Linux Kernel</a></h1>



<p class="blurb">6.18.50</p>







<search id="searchbox" style="display: none" role="search">
  <h3 id="searchlabel">Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
      <input type="submit" value="Go" />
    </form>
    </div>
</search>
<script>document.getElementById('searchbox').style.display = "block"</script>


<p>
<h3 class="kernel-toc-contents">Contents</h3>
<input type="checkbox" class="kernel-toc-toggle" id = "kernel-toc-toggle" checked>
<label class="kernel-toc-title" for="kernel-toc-toggle"></label>

<div class="kerneltoc" id="kerneltoc">
<ul>
<li class="toctree-l1"><a class="reference internal" href="../process/development-process.html">Development process</a></li>
<li class="toctree-l1"><a class="reference internal" href="../process/submitting-patches.html">Submitting patches</a></li>
<li class="toctree-l1"><a class="reference internal" href="../process/code-of-conduct.html">Code of conduct</a></li>
<li class="toctree-l1"><a class="reference internal" href="../maintainer/index.html">Maintainer handbook</a></li>
<li class="toctree-l1"><a class="reference internal" href="../process/index.html">All development-process docs</a></li>
</ul>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../core-api/index.html">Core API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../driver-api/index.html">Driver APIs</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../subsystem-apis.html">Subsystems</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../subsystem-apis.html#core-subsystems">Core subsystems</a></li>
<li class="toctree-l2"><a class="reference internal" href="../subsystem-apis.html#human-interfaces">Human interfaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="../subsystem-apis.html#networking-interfaces">Networking interfaces</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="../subsystem-apis.html#storage-interfaces">Storage interfaces</a><ul class="current">
<li class="toctree-l3 current"><a class="reference internal" href="index.html">Filesystems in the Linux kernel</a></li>
<li class="toctree-l3"><a class="reference internal" href="../block/index.html">Block</a></li>
<li class="toctree-l3"><a class="reference internal" href="../cdrom/index.html">CD-ROM</a></li>
<li class="toctree-l3"><a class="reference internal" href="../scsi/index.html">SCSI Subsystem</a></li>
<li class="toctree-l3"><a class="reference internal" href="../target/index.html">TCM Virtual Device</a></li>
<li class="toctree-l3"><a class="reference internal" href="../nvme/index.html">NVMe Subsystem</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../subsystem-apis.html#other-subsystems">Other subsystems</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../locking/index.html">Locking</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../process/license-rules.html">Licensing rules</a></li>
<li class="toctree-l1"><a class="reference internal" href="../doc-guide/index.html">Writing documentation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../dev-tools/index.html">Development tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="../dev-tools/testing-overview.html">Testing guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../kernel-hacking/index.html">Hacking guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../trace/index.html">Tracing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../fault-injection/index.html">Fault injection</a></li>
<li class="toctree-l1"><a class="reference internal" href="../livepatch/index.html">Livepatching</a></li>
<li class="toctree-l1"><a class="reference internal" href="../rust/index.html">Rust</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../admin-guide/index.html">Administration</a></li>
<li class="toctree-l1"><a class="reference internal" href="../kbuild/index.html">Build system</a></li>
<li class="toctree-l1"><a class="reference internal" href="../admin-guide/reporting-issues.html">Reporting issues</a></li>
<li class="toctree-l1"><a class="reference internal" href="../tools/index.html">Userspace tools</a></li>
<li class="toctree-l1"><a class="reference internal" href="../userspace-api/index.html">Userspace API</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../firmware-guide/index.html">Firmware</a></li>
<li class="toctree-l1"><a class="reference internal" href="../devicetree/index.html">Firmware and Devicetree</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../arch/index.html">CPU architectures</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../staging/index.html">Unsorted documentation</a></li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../translations/index.html">Translations</a></li>
</ul>

</div>

<script type="text/javascript"> <!--
  var sbar = document.getElementsByClassName("sphinxsidebar")[0];
  let currents = document.getElementsByClassName("current")
  if (currents.length) {
    sbar.scrollTop = currents[currents.length - 1].offsetTop;
  }
  --> </script>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/filesystems/fscrypt.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
        </div>
      </div>
      <div class="documentwrapper">
        <div class="bodywrapper">
          

          <div class="body" role="main">
            
  



<section id="filesystem-level-encryption-fscrypt">
<h1>Filesystem-level encryption (fscrypt)<a class="headerlink" href="#filesystem-level-encryption-fscrypt" title="Link to this heading">¶</a></h1>
<section id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Link to this heading">¶</a></h2>
<p>fscrypt is a library which filesystems can hook into to support
transparent encryption of files and directories.</p>
<p>Note: “fscrypt” in this document refers to the kernel-level portion,
implemented in <code class="docutils literal notranslate"><span class="pre">fs/crypto/</span></code>, as opposed to the userspace tool
<a class="reference external" href="https://github.com/google/fscrypt">fscrypt</a>.  This document only
covers the kernel-level portion.  For command-line examples of how to
use encryption, see the documentation for the userspace tool <a class="reference external" href="https://github.com/google/fscrypt">fscrypt</a>.  Also, it is recommended to use
the fscrypt userspace tool, or other existing userspace tools such as
<a class="reference external" href="https://github.com/google/fscryptctl">fscryptctl</a> or <a class="reference external" href="https://source.android.com/security/encryption/file-based">Android’s key
management system</a>, 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.)</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
</section>
<section id="threat-model">
<h2>Threat model<a class="headerlink" href="#threat-model" title="Link to this heading">¶</a></h2>
<section id="offline-attacks">
<h3>Offline attacks<a class="headerlink" href="#offline-attacks" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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.</p>
</section>
<section id="online-attacks">
<h3>Online attacks<a class="headerlink" href="#online-attacks" title="Link to this heading">¶</a></h3>
<p>fscrypt (and storage encryption in general) can only provide limited
protection against online attacks.  In detail:</p>
<section id="side-channel-attacks">
<h4>Side-channel attacks<a class="headerlink" href="#side-channel-attacks" title="Link to this heading">¶</a></h4>
<p>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.</p>
</section>
<section id="unauthorized-file-access">
<h4>Unauthorized file access<a class="headerlink" href="#unauthorized-file-access" title="Link to this heading">¶</a></h4>
<p>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.</p>
<p>(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 <em>not</em> 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 <em>code</em> and therefore would be largely redundant
with the wide variety of access control mechanisms already available.)</p>
</section>
<section id="read-only-kernel-memory-compromise">
<h4>Read-only kernel memory compromise<a class="headerlink" href="#read-only-kernel-memory-compromise" title="Link to this heading">¶</a></h4>
<p>Unless <a class="reference internal" href="#hardware-wrapped-keys">hardware-wrapped keys</a> 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.</p>
<p>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.</p>
<p>In addition, fscrypt allows encryption keys to be removed from the
kernel, which may protect them from later compromise.</p>
<p>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.</p>
<p>However, these ioctls have some limitations:</p>
<ul class="simple">
<li><p>Per-file keys for in-use files will <em>not</em> 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.</p></li>
<li><p>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 <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">mlock()</span></code>ing memory
containing keys to prevent it from being swapped out.</p></li>
<li><p>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.</p></li>
<li><p>Secret keys might still exist in CPU registers or in other places
not explicitly considered here.</p></li>
</ul>
</section>
<section id="full-system-compromise">
<h4>Full system compromise<a class="headerlink" href="#full-system-compromise" title="Link to this heading">¶</a></h4>
<p>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.)</p>
<p>However, if <a class="reference internal" href="#hardware-wrapped-keys">hardware-wrapped keys</a> 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.</p>
</section>
<section id="limitations-of-v1-policies">
<h4>Limitations of v1 policies<a class="headerlink" href="#limitations-of-v1-policies" title="Link to this heading">¶</a></h4>
<p>v1 encryption policies have some weaknesses with respect to online
attacks:</p>
<ul class="simple">
<li><p>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”.</p></li>
<li><p>A compromise of a per-file key also compromises the master key from
which it was derived.</p></li>
<li><p>Non-root users cannot securely remove encryption keys.</p></li>
</ul>
<p>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.</p>
</section>
</section>
</section>
<section id="key-hierarchy">
<h2>Key hierarchy<a class="headerlink" href="#key-hierarchy" title="Link to this heading">¶</a></h2>
<p>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 <a class="reference internal" href="#hardware-wrapped-keys">Hardware-wrapped keys</a>.</p>
<section id="master-keys">
<h3>Master Keys<a class="headerlink" href="#master-keys" title="Link to this heading">¶</a></h3>
<p>Each encrypted directory tree is protected by a <em>master key</em>.  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.</p>
<p>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.</p>
<p>Master keys must be real cryptographic keys, i.e. indistinguishable
from random bytestrings of the same length.  This implies that users
<strong>must not</strong> 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.</p>
<p>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.</p>
</section>
<section id="key-derivation-function">
<h3>Key derivation function<a class="headerlink" href="#key-derivation-function" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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 <strong>must not</strong> 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.)</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
</section>
<section id="per-file-encryption-keys">
<h3>Per-file encryption keys<a class="headerlink" href="#per-file-encryption-keys" title="Link to this heading">¶</a></h3>
<p>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 <a class="reference internal" href="#key-derivation-function">Key
derivation function</a>) to derive the file’s key from the master key
and nonce.</p>
<p>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
<a class="reference external" href="https://github.com/google/fscrypt">fscrypt</a> tool.</p>
</section>
<section id="direct-key-policies">
<h3>DIRECT_KEY policies<a class="headerlink" href="#direct-key-policies" title="Link to this heading">¶</a></h3>
<p>The Adiantum encryption mode (see <a class="reference internal" href="#encryption-modes-and-usage">Encryption modes and usage</a>) 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.</p>
<p>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:</p>
<ul class="simple">
<li><p>For v1 encryption policies, the encryption is done directly with the
master key.  Because of this, users <strong>must not</strong> use the same master
key for any other purpose, even for other v1 policies.</p></li>
<li><p>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.</p></li>
</ul>
</section>
<section id="iv-ino-lblk-64-policies">
<h3>IV_INO_LBLK_64 policies<a class="headerlink" href="#iv-ino-lblk-64-policies" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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.</p>
</section>
<section id="iv-ino-lblk-32-policies">
<h3>IV_INO_LBLK_32 policies<a class="headerlink" href="#iv-ino-lblk-32-policies" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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.</p>
</section>
<section id="key-identifiers">
<h3>Key identifiers<a class="headerlink" href="#key-identifiers" title="Link to this heading">¶</a></h3>
<p>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.</p>
</section>
<section id="dirhash-keys">
<h3>Dirhash keys<a class="headerlink" href="#dirhash-keys" title="Link to this heading">¶</a></h3>
<p>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.</p>
</section>
</section>
<section id="encryption-modes-and-usage">
<h2>Encryption modes and usage<a class="headerlink" href="#encryption-modes-and-usage" title="Link to this heading">¶</a></h2>
<p>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.</p>
<section id="supported-modes">
<h3>Supported modes<a class="headerlink" href="#supported-modes" title="Link to this heading">¶</a></h3>
<p>Currently, the following pairs of encryption modes are supported:</p>
<ul class="simple">
<li><p>AES-256-XTS for contents and AES-256-CBC-CTS for filenames</p></li>
<li><p>AES-256-XTS for contents and AES-256-HCTR2 for filenames</p></li>
<li><p>Adiantum for both contents and filenames</p></li>
<li><p>AES-128-CBC-ESSIV for contents and AES-128-CBC-CTS for filenames</p></li>
<li><p>SM4-XTS for contents and SM4-CBC-CTS for filenames</p></li>
</ul>
<p>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.</p>
<p>Authenticated encryption modes are not currently supported because of
the difficulty of dealing with ciphertext expansion.  Therefore,
contents encryption uses a block cipher in <a class="reference external" href="https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS">XTS mode</a> or
<a class="reference external" href="https://en.wikipedia.org/wiki/Disk_encryption_theory#Encrypted_salt-sector_initialization_vector_(ESSIV)">CBC-ESSIV mode</a>,
or a wide-block cipher.  Filenames encryption uses a
block cipher in <a class="reference external" href="https://en.wikipedia.org/wiki/Ciphertext_stealing">CBC-CTS mode</a> or a wide-block
cipher.</p>
<p>The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default.
It is also the only option that is <em>guaranteed</em> to always be supported
if the kernel supports fscrypt at all; see <a class="reference internal" href="#kernel-config-options">Kernel config options</a>.</p>
<p>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
<em>wide-block cipher</em>, also called a tweakable super-pseudorandom
permutation, has the property that changing one bit scrambles the
entire result.)  As described in <a class="reference internal" href="#filenames-encryption">Filenames encryption</a>, 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 <a class="reference external" href="https://eprint.iacr.org/2021/1441.pdf">the HCTR2 paper</a>.</p>
<p>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
<a class="reference external" href="https://eprint.iacr.org/2018/720.pdf">the Adiantum paper</a>.</p>
<p>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.</p>
<p>The remaining mode pairs are the “national pride ciphers”:</p>
<ul class="simple">
<li><p>(SM4-XTS, SM4-CBC-CTS)</p></li>
</ul>
<p>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.</p>
</section>
<section id="kernel-config-options">
<h3>Kernel config options<a class="headerlink" href="#kernel-config-options" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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 <a class="reference internal" href="#inline-encryption-support">Inline encryption support</a>); in that case,
the file contents mode doesn’t need to supported in the kernel crypto
API, but the filenames mode still does.</p>
<ul class="simple">
<li><dl class="simple">
<dt>AES-256-XTS and AES-256-CBC-CTS</dt><dd><ul>
<li><dl class="simple">
<dt>Recommended:</dt><dd><ul>
<li><p>arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK</p></li>
<li><p>x86: CONFIG_CRYPTO_AES_NI_INTEL</p></li>
</ul>
</dd>
</dl>
</li>
</ul>
</dd>
</dl>
</li>
<li><dl class="simple">
<dt>AES-256-HCTR2</dt><dd><ul>
<li><dl class="simple">
<dt>Mandatory:</dt><dd><ul>
<li><p>CONFIG_CRYPTO_HCTR2</p></li>
</ul>
</dd>
</dl>
</li>
<li><dl class="simple">
<dt>Recommended:</dt><dd><ul>
<li><p>arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK</p></li>
<li><p>arm64: CONFIG_CRYPTO_POLYVAL_ARM64_CE</p></li>
<li><p>x86: CONFIG_CRYPTO_AES_NI_INTEL</p></li>
<li><p>x86: CONFIG_CRYPTO_POLYVAL_CLMUL_NI</p></li>
</ul>
</dd>
</dl>
</li>
</ul>
</dd>
</dl>
</li>
<li><dl class="simple">
<dt>Adiantum</dt><dd><ul>
<li><dl class="simple">
<dt>Mandatory:</dt><dd><ul>
<li><p>CONFIG_CRYPTO_ADIANTUM</p></li>
</ul>
</dd>
</dl>
</li>
<li><dl class="simple">
<dt>Recommended:</dt><dd><ul>
<li><p>arm32: CONFIG_CRYPTO_NHPOLY1305_NEON</p></li>
<li><p>arm64: CONFIG_CRYPTO_NHPOLY1305_NEON</p></li>
<li><p>x86: CONFIG_CRYPTO_NHPOLY1305_SSE2</p></li>
<li><p>x86: CONFIG_CRYPTO_NHPOLY1305_AVX2</p></li>
</ul>
</dd>
</dl>
</li>
</ul>
</dd>
</dl>
</li>
<li><dl class="simple">
<dt>AES-128-CBC-ESSIV and AES-128-CBC-CTS:</dt><dd><ul>
<li><dl class="simple">
<dt>Mandatory:</dt><dd><ul>
<li><p>CONFIG_CRYPTO_ESSIV</p></li>
<li><p>CONFIG_CRYPTO_SHA256 or another SHA-256 implementation</p></li>
</ul>
</dd>
</dl>
</li>
<li><dl class="simple">
<dt>Recommended:</dt><dd><ul>
<li><p>AES-CBC acceleration</p></li>
</ul>
</dd>
</dl>
</li>
</ul>
</dd>
</dl>
</li>
</ul>
</section>
<section id="contents-encryption">
<h3>Contents encryption<a class="headerlink" href="#contents-encryption" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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.</p>
<p>There are two cases for the sizes of the data units:</p>
<ul class="simple">
<li><p>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 <code class="docutils literal notranslate"><span class="pre">log2_data_unit_size</span></code> field of
the encryption policy; see <a class="reference internal" href="#fs-ioc-set-encryption-policy">FS_IOC_SET_ENCRYPTION_POLICY</a>.</p></li>
<li><p>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.</p></li>
</ul>
<p>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.</p>
<p>As mentioned in <a class="reference internal" href="#key-hierarchy">Key hierarchy</a>, 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:</p>
<ul class="simple">
<li><p>With <a class="reference internal" href="#direct-key-policies">DIRECT_KEY policies</a>, the data unit index is placed in bits
0-63 of the IV, and the file’s nonce is placed in bits 64-191.</p></li>
<li><p>With <a class="reference internal" href="#iv-ino-lblk-64-policies">IV_INO_LBLK_64 policies</a>, 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.</p></li>
<li><p>With <a class="reference internal" href="#iv-ino-lblk-32-policies">IV_INO_LBLK_32 policies</a>, 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.</p></li>
</ul>
<p>The byte order of the IV is always little endian.</p>
<p>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.</p>
</section>
<section id="filenames-encryption">
<h3>Filenames encryption<a class="headerlink" href="#filenames-encryption" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>However, each encrypted directory still uses a unique key, or
alternatively has the file’s nonce (for <a class="reference internal" href="#direct-key-policies">DIRECT_KEY policies</a>) or
inode number (for <a class="reference internal" href="#iv-ino-lblk-64-policies">IV_INO_LBLK_64 policies</a>) included in the IVs.
Thus, IV reuse is limited to within a single directory.</p>
<p>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.</p>
<p>All supported filenames encryption modes accept any plaintext length
&gt;= 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 (<code class="docutils literal notranslate"><span class="pre">\0</span></code>) is
not otherwise a valid character in filenames, the padding will never
produce duplicate plaintexts.</p>
<p>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.</p>
</section>
</section>
<section id="user-api">
<h2>User API<a class="headerlink" href="#user-api" title="Link to this heading">¶</a></h2>
<section id="setting-an-encryption-policy">
<h3>Setting an encryption policy<a class="headerlink" href="#setting-an-encryption-policy" title="Link to this heading">¶</a></h3>
<section id="fs-ioc-set-encryption-policy">
<h4>FS_IOC_SET_ENCRYPTION_POLICY<a class="headerlink" href="#fs-ioc-set-encryption-policy" title="Link to this heading">¶</a></h4>
<p>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
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v1</span></code> or <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v2</span></code>, defined as
follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>#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];
};
</pre></div>
</div>
<p>This structure must be initialized as follows:</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">version</span></code> must be FSCRYPT_POLICY_V1 (0) if
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v1</span></code> is used or FSCRYPT_POLICY_V2 (2) if
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v2</span></code> 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.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">contents_encryption_mode</span></code> and <code class="docutils literal notranslate"><span class="pre">filenames_encryption_mode</span></code> must
be set to constants from <code class="docutils literal notranslate"><span class="pre">&lt;linux/fscrypt.h&gt;</span></code> which identify the
encryption modes to use.  If unsure, use FSCRYPT_MODE_AES_256_XTS
(1) for <code class="docutils literal notranslate"><span class="pre">contents_encryption_mode</span></code> and FSCRYPT_MODE_AES_256_CTS
(4) for <code class="docutils literal notranslate"><span class="pre">filenames_encryption_mode</span></code>.  For details, see <a class="reference internal" href="#encryption-modes-and-usage">Encryption
modes and usage</a>.</p>
<p>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 <a class="reference internal" href="#supported-modes">Supported modes</a>.</p>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">flags</span></code> contains optional flags from <code class="docutils literal notranslate"><span class="pre">&lt;linux/fscrypt.h&gt;</span></code>:</p>
<ul class="simple">
<li><p>FSCRYPT_POLICY_FLAGS_PAD_*: The amount of NUL padding to use when
encrypting filenames.  If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32
(0x3).</p></li>
<li><p>FSCRYPT_POLICY_FLAG_DIRECT_KEY: See <a class="reference internal" href="#direct-key-policies">DIRECT_KEY policies</a>.</p></li>
<li><p>FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: See <a class="reference internal" href="#iv-ino-lblk-64-policies">IV_INO_LBLK_64
policies</a>.</p></li>
<li><p>FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: See <a class="reference internal" href="#iv-ino-lblk-32-policies">IV_INO_LBLK_32
policies</a>.</p></li>
</ul>
<p>v1 encryption policies only support the PAD_* and DIRECT_KEY flags.
The other flags are only supported by v2 encryption policies.</p>
<p>The DIRECT_KEY, IV_INO_LBLK_64, and IV_INO_LBLK_32 flags are
mutually exclusive.</p>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">log2_data_unit_size</span></code> 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
<code class="docutils literal notranslate"><span class="pre">log2_data_unit_size</span></code> 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.</p>
<p>Not all filesystems support setting <code class="docutils literal notranslate"><span class="pre">log2_data_unit_size</span></code>.  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.</p>
<p>The main use case for <code class="docutils literal notranslate"><span class="pre">log2_data_unit_size</span></code> 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.  <code class="docutils literal notranslate"><span class="pre">/sys/block/$disk/queue/crypto/</span></code> may be
useful for checking which data unit sizes are supported by a
particular system’s inline encryption hardware.</p>
<p>Leave this field zeroed unless you are certain you need it.  Using
an unnecessarily small data unit size reduces performance.</p>
</li>
<li><p>For v2 encryption policies, <code class="docutils literal notranslate"><span class="pre">__reserved</span></code> must be zeroed.</p></li>
<li><p>For v1 encryption policies, <code class="docutils literal notranslate"><span class="pre">master_key_descriptor</span></code> specifies how
to find the master key in a keyring; see <a class="reference internal" href="#adding-keys">Adding keys</a>.  It is up
to userspace to choose a unique <code class="docutils literal notranslate"><span class="pre">master_key_descriptor</span></code> for each
master key.  The e4crypt and fscrypt tools use the first 8 bytes of
<code class="docutils literal notranslate"><span class="pre">SHA-512(SHA-512(master_key))</span></code>, 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.</p>
<p>For v2 encryption policies, <code class="docutils literal notranslate"><span class="pre">master_key_descriptor</span></code> has been
replaced with <code class="docutils literal notranslate"><span class="pre">master_key_identifier</span></code>, which is longer and cannot
be arbitrarily chosen.  Instead, the key must first be added using
<a class="reference internal" href="#fs-ioc-add-encryption-key">FS_IOC_ADD_ENCRYPTION_KEY</a>.  Then, the <code class="docutils literal notranslate"><span class="pre">key_spec.u.identifier</span></code>
the kernel returned in the <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_add_key_arg</span></code> must
be used as the <code class="docutils literal notranslate"><span class="pre">master_key_identifier</span></code> in
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v2</span></code>.</p>
</li>
</ul>
<p>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 <a class="reference internal" href="#adding-keys">Adding keys</a>, 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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">EACCES</span></code>: 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</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EEXIST</span></code>: the file is already encrypted with an encryption policy
different from the one specified</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EINVAL</span></code>: 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).</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOKEY</span></code>: a v2 encryption policy was specified, but the key with
the specified <code class="docutils literal notranslate"><span class="pre">master_key_identifier</span></code> has not been added, nor does
the process have the CAP_FOWNER capability in the initial user
namespace</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTDIR</span></code>: the file is unencrypted and is a regular file, not a
directory</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTEMPTY</span></code>: the file is unencrypted and is a nonempty directory</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTTY</span></code>: this type of filesystem does not implement encryption</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EOPNOTSUPP</span></code>: 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 <code class="docutils literal notranslate"><span class="pre">tune2fs</span> <span class="pre">-O</span> <span class="pre">encrypt</span></code> or <code class="docutils literal notranslate"><span class="pre">mkfs.ext4</span> <span class="pre">-O</span>
<span class="pre">encrypt</span></code>.)</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EPERM</span></code>: this directory may not be encrypted, e.g. because it is
the root directory of an ext4 filesystem</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EROFS</span></code>: the filesystem is readonly</p></li>
</ul>
</section>
</section>
<section id="getting-an-encryption-policy">
<h3>Getting an encryption policy<a class="headerlink" href="#getting-an-encryption-policy" title="Link to this heading">¶</a></h3>
<p>Two ioctls are available to get a file’s encryption policy:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#fs-ioc-get-encryption-policy-ex">FS_IOC_GET_ENCRYPTION_POLICY_EX</a></p></li>
<li><p><a class="reference internal" href="#fs-ioc-get-encryption-policy">FS_IOC_GET_ENCRYPTION_POLICY</a></p></li>
</ul>
<p>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.</p>
<section id="fs-ioc-get-encryption-policy-ex">
<h4>FS_IOC_GET_ENCRYPTION_POLICY_EX<a class="headerlink" href="#fs-ioc-get-encryption-policy-ex" title="Link to this heading">¶</a></h4>
<p>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 <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_get_policy_ex_arg</span></code>,
defined as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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 */
};
</pre></div>
</div>
<p>The caller must initialize <code class="docutils literal notranslate"><span class="pre">policy_size</span></code> to the size available for
the policy struct, i.e. <code class="docutils literal notranslate"><span class="pre">sizeof(arg.policy)</span></code>.</p>
<p>On success, the policy <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">is</span></code> returned in <code class="docutils literal notranslate"><span class="pre">policy</span></code>, and its
actual size is returned in <code class="docutils literal notranslate"><span class="pre">policy_size</span></code>.  <code class="docutils literal notranslate"><span class="pre">policy.version</span></code> 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).</p>
<p>FS_IOC_GET_ENCRYPTION_POLICY_EX can fail with the following errors:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">EINVAL</span></code>: the file is encrypted, but it uses an unrecognized
encryption policy version</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENODATA</span></code>: the file is not encrypted</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTTY</span></code>: 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)</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EOPNOTSUPP</span></code>: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EOVERFLOW</span></code>: the file is encrypted and uses a recognized
encryption policy version, but the policy <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">does</span></code> not fit into
the provided buffer</p></li>
</ul>
<p>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 <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">statx()</span></code> system call and
check for STATX_ATTR_ENCRYPTED in stx_attributes.</p>
</section>
<section id="fs-ioc-get-encryption-policy">
<h4>FS_IOC_GET_ENCRYPTION_POLICY<a class="headerlink" href="#fs-ioc-get-encryption-policy" title="Link to this heading">¶</a></h4>
<p>The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve the
encryption policy, if any, for a directory or regular file.  However,
unlike <a class="reference internal" href="#fs-ioc-get-encryption-policy-ex">FS_IOC_GET_ENCRYPTION_POLICY_EX</a>,
FS_IOC_GET_ENCRYPTION_POLICY only supports the original policy
version.  It takes in a pointer directly to <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v1</span></code>
rather than <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_get_policy_ex_arg</span></code>.</p>
<p>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 <code class="docutils literal notranslate"><span class="pre">EINVAL</span></code> if the file is
encrypted using a newer encryption policy version.</p>
</section>
</section>
<section id="getting-the-per-filesystem-salt">
<h3>Getting the per-filesystem salt<a class="headerlink" href="#getting-the-per-filesystem-salt" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>FS_IOC_GET_ENCRYPTION_PWSALT is deprecated.  Instead, prefer to
generate and manage any needed salt(s) in userspace.</p>
</section>
<section id="getting-a-file-s-encryption-nonce">
<h3>Getting a file’s encryption nonce<a class="headerlink" href="#getting-a-file-s-encryption-nonce" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>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.</p>
</section>
<section id="adding-keys">
<h3>Adding keys<a class="headerlink" href="#adding-keys" title="Link to this heading">¶</a></h3>
<section id="fs-ioc-add-encryption-key">
<h4>FS_IOC_ADD_ENCRYPTION_KEY<a class="headerlink" href="#fs-ioc-add-encryption-key" title="Link to this heading">¶</a></h4>
<p>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 <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_add_key_arg</span></code>, defined as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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[];
};
</pre></div>
</div>
<p><code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_add_key_arg</span></code> must be zeroed, then initialized
as follows:</p>
<ul>
<li><p>If the key is being added for use by v1 encryption policies, then
<code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code> must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, and
<code class="docutils literal notranslate"><span class="pre">key_spec.u.descriptor</span></code> must contain the descriptor of the key
being added, corresponding to the value in the
<code class="docutils literal notranslate"><span class="pre">master_key_descriptor</span></code> field of <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_policy_v1</span></code>.
To add this type of key, the calling process must have the
CAP_SYS_ADMIN capability in the initial user namespace.</p>
<p>Alternatively, if the key is being added for use by v2 encryption
policies, then <code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code> must contain
FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, and <code class="docutils literal notranslate"><span class="pre">key_spec.u.identifier</span></code> is
an <em>output</em> 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
<code class="docutils literal notranslate"><span class="pre">Documentation/security/keys/core.rst</span></code>).</p>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">raw_size</span></code> must be the size of the <code class="docutils literal notranslate"><span class="pre">raw</span></code> key provided, in bytes.
Alternatively, if <code class="docutils literal notranslate"><span class="pre">key_id</span></code> is nonzero, this field must be 0, since
in that case the size is implied by the specified Linux keyring key.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">key_id</span></code> is 0 if the key is given directly in the <code class="docutils literal notranslate"><span class="pre">raw</span></code> field.
Otherwise <code class="docutils literal notranslate"><span class="pre">key_id</span></code> is the ID of a Linux keyring key of type
“fscrypt-provisioning” whose payload is <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span>
<span class="pre">fscrypt_provisioning_key_payload</span></code> whose <code class="docutils literal notranslate"><span class="pre">raw</span></code> field contains the
key, whose <code class="docutils literal notranslate"><span class="pre">type</span></code> field matches <code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code>, and whose
<code class="docutils literal notranslate"><span class="pre">flags</span></code> field matches <code class="docutils literal notranslate"><span class="pre">flags</span></code>.  Since <code class="docutils literal notranslate"><span class="pre">raw</span></code> is
variable-length, the total size of this key’s payload must be
<code class="docutils literal notranslate"><span class="pre">sizeof(struct</span> <span class="pre">fscrypt_provisioning_key_payload)</span></code> plus the number
of key bytes.  The process must have Search permission on this key.</p>
<p>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.</p>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">flags</span></code> contains optional flags from <code class="docutils literal notranslate"><span class="pre">&lt;linux/fscrypt.h&gt;</span></code>:</p>
<ul class="simple">
<li><p>FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED: This denotes that the key is a
hardware-wrapped key.  See <a class="reference internal" href="#hardware-wrapped-keys">Hardware-wrapped keys</a>.  This flag
can’t be used if FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR is used.</p></li>
</ul>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">raw</span></code> is a variable-length field which must contain the actual
key, <code class="docutils literal notranslate"><span class="pre">raw_size</span></code> bytes long.  Alternatively, if <code class="docutils literal notranslate"><span class="pre">key_id</span></code> is
nonzero, then this field is unused.  Note that despite being named
<code class="docutils literal notranslate"><span class="pre">raw</span></code>, if FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED is specified then it
will contain a wrapped key, not a raw key.</p></li>
</ul>
<p>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
<a class="reference internal" href="#fs-ioc-remove-encryption-key-all-users">FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS</a>.</p>
<p>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
<em>again</em>, 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).</p>
<p>FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim to
the key was either added or already exists.</p>
<p>FS_IOC_ADD_ENCRYPTION_KEY can fail with the following errors:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">EACCES</span></code>: 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.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EBADMSG</span></code>: invalid hardware-wrapped key</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EDQUOT</span></code>: the key quota for this user would be exceeded by adding
the key</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EINVAL</span></code>: invalid key size or key specifier type, or reserved bits
were set</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EKEYREJECTED</span></code>: the key was specified by Linux key ID, but the key
has the wrong type</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOKEY</span></code>: the key was specified by Linux key ID, but no key exists
with that ID</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTTY</span></code>: this type of filesystem does not implement encryption</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EOPNOTSUPP</span></code>: 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</p></li>
</ul>
</section>
<section id="legacy-method">
<h4>Legacy method<a class="headerlink" href="#legacy-method" title="Link to this heading">¶</a></h4>
<p>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.</p>
<p>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 <a class="reference internal" href="#removing-keys">Removing keys</a>),
so for removing a key a workaround such as <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">keyctl_unlink()</span></code> in
combination with <code class="docutils literal notranslate"><span class="pre">sync;</span> <span class="pre">echo</span> <span class="pre">2</span> <span class="pre">&gt;</span> <span class="pre">/proc/sys/vm/drop_caches</span></code> 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 <code class="docutils literal notranslate"><span class="pre">sudo</span></code> command, need to
access encrypted files.</p>
<p>Nevertheless, to add a key to one of the process-subscribed keyrings,
the <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">add_key()</span></code> system call can be used (see:
<code class="docutils literal notranslate"><span class="pre">Documentation/security/keys/core.rst</span></code>).  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
<code class="docutils literal notranslate"><span class="pre">master_key_descriptor</span></code> that was set in the encryption policy.  The
key payload must conform to the following structure:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>#define FSCRYPT_MAX_KEY_SIZE            64

struct fscrypt_key {
        __u32 mode;
        __u8 raw[FSCRYPT_MAX_KEY_SIZE];
        __u32 size;
};
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">mode</span></code> is ignored; just set it to 0.  The actual key is provided in
<code class="docutils literal notranslate"><span class="pre">raw</span></code> with <code class="docutils literal notranslate"><span class="pre">size</span></code> indicating its size in bytes.  That is, the
bytes <code class="docutils literal notranslate"><span class="pre">raw[0..size-1]</span></code> (inclusive) are the actual key.</p>
<p>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.</p>
</section>
</section>
<section id="removing-keys">
<h3>Removing keys<a class="headerlink" href="#removing-keys" title="Link to this heading">¶</a></h3>
<p>Two ioctls are available for removing a key that was added by
<a class="reference internal" href="#fs-ioc-add-encryption-key">FS_IOC_ADD_ENCRYPTION_KEY</a>:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#fs-ioc-remove-encryption-key">FS_IOC_REMOVE_ENCRYPTION_KEY</a></p></li>
<li><p><a class="reference internal" href="#fs-ioc-remove-encryption-key-all-users">FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS</a></p></li>
</ul>
<p>These two ioctls differ only in cases where v2 policy keys are added
or removed by non-root users.</p>
<p>These ioctls don’t work on keys that were added via the legacy
process-subscribed keyrings mechanism.</p>
<p>Before using these ioctls, read the <a class="reference internal" href="#online-attacks">Online attacks</a> section for a
discussion of the security goals and limitations of these ioctls.</p>
<section id="fs-ioc-remove-encryption-key">
<h4>FS_IOC_REMOVE_ENCRYPTION_KEY<a class="headerlink" href="#fs-ioc-remove-encryption-key" title="Link to this heading">¶</a></h4>
<p>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 <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_remove_key_arg</span></code>, defined
as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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];
};
</pre></div>
</div>
<p>This structure must be zeroed, then initialized as follows:</p>
<ul>
<li><p>The key to remove is specified by <code class="docutils literal notranslate"><span class="pre">key_spec</span></code>:</p>
<blockquote>
<div><ul class="simple">
<li><p>To remove a key used by v1 encryption policies, set
<code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code> to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
in <code class="docutils literal notranslate"><span class="pre">key_spec.u.descriptor</span></code>.  To remove this type of key, the
calling process must have the CAP_SYS_ADMIN capability in the
initial user namespace.</p></li>
<li><p>To remove a key used by v2 encryption policies, set
<code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code> to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
in <code class="docutils literal notranslate"><span class="pre">key_spec.u.identifier</span></code>.</p></li>
</ul>
</div></blockquote>
</li>
</ul>
<p>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.</p>
<p>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 <em>both</em> are removed is the key really removed.  (Think of it like
unlinking a file that may have hard links.)</p>
<p>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.</p>
<p>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, <code class="docutils literal notranslate"><span class="pre">removal_status_flags</span></code> is filled in with the
following informational status flags:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY</span></code>: 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.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS</span></code>: set if only the
user’s claim to the key was removed, not the key itself</p></li>
</ul>
<p>FS_IOC_REMOVE_ENCRYPTION_KEY can fail with the following errors:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">EACCES</span></code>: 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</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EINVAL</span></code>: invalid key specifier type, or reserved bits were set</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOKEY</span></code>: 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).</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTTY</span></code>: this type of filesystem does not implement encryption</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EOPNOTSUPP</span></code>: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it</p></li>
</ul>
</section>
<section id="fs-ioc-remove-encryption-key-all-users">
<h4>FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS<a class="headerlink" href="#fs-ioc-remove-encryption-key-all-users" title="Link to this heading">¶</a></h4>
<p>FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same as
<a class="reference internal" href="#fs-ioc-remove-encryption-key">FS_IOC_REMOVE_ENCRYPTION_KEY</a>, 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.</p>
<p>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.</p>
</section>
</section>
<section id="getting-key-status">
<h3>Getting key status<a class="headerlink" href="#getting-key-status" title="Link to this heading">¶</a></h3>
<section id="fs-ioc-get-encryption-key-status">
<h4>FS_IOC_GET_ENCRYPTION_KEY_STATUS<a class="headerlink" href="#fs-ioc-get-encryption-key-status" title="Link to this heading">¶</a></h4>
<p>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
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_get_key_status_arg</span></code>, defined as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>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];
};
</pre></div>
</div>
<p>The caller must zero all input fields, then fill in <code class="docutils literal notranslate"><span class="pre">key_spec</span></code>:</p>
<blockquote>
<div><ul class="simple">
<li><p>To get the status of a key for v1 encryption policies, set
<code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code> to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill
in <code class="docutils literal notranslate"><span class="pre">key_spec.u.descriptor</span></code>.</p></li>
<li><p>To get the status of a key for v2 encryption policies, set
<code class="docutils literal notranslate"><span class="pre">key_spec.type</span></code> to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill
in <code class="docutils literal notranslate"><span class="pre">key_spec.u.identifier</span></code>.</p></li>
</ul>
</div></blockquote>
<p>On success, 0 is returned and the kernel fills in the output fields:</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">status</span></code> 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.,
<a class="reference internal" href="#fs-ioc-remove-encryption-key">FS_IOC_REMOVE_ENCRYPTION_KEY</a> returned 0 but set the informational
status flag FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">status_flags</span></code> can contain the following flags:</p>
<blockquote>
<div><ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF</span></code> indicates that the key
has added by the current user.  This is only set for keys
identified by <code class="docutils literal notranslate"><span class="pre">identifier</span></code> rather than by <code class="docutils literal notranslate"><span class="pre">descriptor</span></code>.</p></li>
</ul>
</div></blockquote>
</li>
<li><p><code class="docutils literal notranslate"><span class="pre">user_count</span></code> specifies the number of users who have added the key.
This is only set for keys identified by <code class="docutils literal notranslate"><span class="pre">identifier</span></code> rather than
by <code class="docutils literal notranslate"><span class="pre">descriptor</span></code>.</p></li>
</ul>
<p>FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">EINVAL</span></code>: invalid key specifier type, or reserved bits were set</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">ENOTTY</span></code>: this type of filesystem does not implement encryption</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">EOPNOTSUPP</span></code>: the kernel was not configured with encryption
support for this filesystem, or the filesystem superblock has not
had encryption enabled on it</p></li>
</ul>
<p>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.</p>
<p>FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys in
the filesystem-level keyring, i.e. the keyring managed by
<a class="reference internal" href="#fs-ioc-add-encryption-key">FS_IOC_ADD_ENCRYPTION_KEY</a> and <a class="reference internal" href="#fs-ioc-remove-encryption-key">FS_IOC_REMOVE_ENCRYPTION_KEY</a>.  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.</p>
</section>
</section>
</section>
<section id="access-semantics">
<h2>Access semantics<a class="headerlink" href="#access-semantics" title="Link to this heading">¶</a></h2>
<section id="with-the-key">
<h3>With the key<a class="headerlink" href="#with-the-key" title="Link to this heading">¶</a></h3>
<p>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:</p>
<ul>
<li><p>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 <a class="reference internal" href="#encryption-policy-enforcement">Encryption policy
enforcement</a>.  Attempts to do so will fail with EXDEV.  However,
encrypted files can be renamed within an encrypted directory, or
into an unencrypted directory.</p>
<p>Note: “moving” an unencrypted file into an encrypted directory, e.g.
with the <cite>mv</cite> 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 <cite>shred</cite> program
may be used to overwrite the source files but isn’t guaranteed to be
effective on all filesystems and storage devices.</p>
</li>
<li><p>Direct I/O is supported on encrypted files only under some
circumstances.  For details, see <a class="reference internal" href="#direct-i-o-support">Direct I/O support</a>.</p></li>
<li><p>The fallocate operations FALLOC_FL_COLLAPSE_RANGE and
FALLOC_FL_INSERT_RANGE are not supported on encrypted files and will
fail with EOPNOTSUPP.</p></li>
<li><p>Online defragmentation of encrypted files is not supported.  The
EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with
EOPNOTSUPP.</p></li>
<li><p>The ext4 filesystem does not support data journaling with encrypted
regular files.  It will fall back to ordered data mode instead.</p></li>
<li><p>DAX (Direct Access) is not supported on encrypted files.</p></li>
<li><p>Encrypted files cannot be used directly as swap files.  To swap to
an encrypted file, set up a loopback device on top of it.
Alternatively, encrypted swap can use a dm-crypt device.</p></li>
<li><p>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).</p></li>
</ul>
<p>Note that mmap <em>is</em> supported.  This is possible because the pagecache
for an encrypted file contains the plaintext, not the ciphertext.</p>
</section>
<section id="without-the-key">
<h3>Without the key<a class="headerlink" href="#without-the-key" title="Link to this heading">¶</a></h3>
<p>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:</p>
<ul>
<li><p>File metadata may be read, e.g. using <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">stat()</span></code>.</p></li>
<li><p>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 <a class="reference internal" href="#filename-hashing-and-encoding">Filename hashing and
encoding</a>.  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 <code class="docutils literal notranslate"><span class="pre">/</span></code> or <code class="docutils literal notranslate"><span class="pre">\0</span></code> characters, and
will uniquely identify directory entries.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">.</span></code> and <code class="docutils literal notranslate"><span class="pre">..</span></code> directory entries are special.  They are always
present and are not encrypted or encoded.</p>
</li>
<li><p>Files may be deleted.  That is, nondirectory files may be deleted
with <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">unlink()</span></code> as usual, and empty directories may be deleted with
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">rmdir()</span></code> as usual.  Therefore, <code class="docutils literal notranslate"><span class="pre">rm</span></code> and <code class="docutils literal notranslate"><span class="pre">rm</span> <span class="pre">-r</span></code> will work as
expected.</p></li>
<li><p>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.</p></li>
</ul>
<p>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(), <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">fallocate()</span></code>, and ioctl(), are also forbidden.</p>
<p>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.</p>
<p>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.</p>
</section>
</section>
<section id="encryption-policy-enforcement">
<h2>Encryption policy enforcement<a class="headerlink" href="#encryption-policy-enforcement" title="Link to this heading">¶</a></h2>
<p>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.</p>
<p>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 -&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">lookup()</span></code> 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.</p>
</section>
<section id="inline-encryption-support">
<h2>Inline encryption support<a class="headerlink" href="#inline-encryption-support" title="Link to this heading">¶</a></h2>
<p>Many newer systems (especially mobile SoCs) have <em>inline encryption
hardware</em> 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 <em>blk-crypto</em>.  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
<a class="reference internal" href="../block/inline-encryption.html#inline-encryption"><span class="std std-ref">Documentation/block/inline-encryption.rst</span></a>.</p>
<p>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.</p>
<p>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.)</p>
<p>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.</p>
<p>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.</p>
<section id="hardware-wrapped-keys">
<h3>Hardware-wrapped keys<a class="headerlink" href="#hardware-wrapped-keys" title="Link to this heading">¶</a></h3>
<p>fscrypt supports using <em>hardware-wrapped keys</em> 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.</p>
<p>Note that hardware-wrapped keys aren’t specific to fscrypt; they are a
block layer feature (part of <em>blk-crypto</em>).  For more details about
hardware-wrapped keys, see the block layer documentation at
<a class="reference internal" href="../block/inline-encryption.html#hardware-wrapped-keys"><span class="std std-ref">Documentation/block/inline-encryption.rst</span></a>.  The rest of this section just focuses on
the details of how fscrypt can use hardware-wrapped keys.</p>
<p>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 <a class="reference internal" href="#fs-ioc-add-encryption-key">FS_IOC_ADD_ENCRYPTION_KEY</a>,
userspace must specify FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED in the
<code class="docutils literal notranslate"><span class="pre">flags</span></code> field of <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_add_key_arg</span></code> and also in the
<code class="docutils literal notranslate"><span class="pre">flags</span></code> field of <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_provisioning_key_payload</span></code> when
applicable.  The key must be in ephemerally-wrapped form, not
long-term wrapped form.</p>
<p>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
<a class="reference internal" href="#iv-ino-lblk-64-policies">IV_INO_LBLK_64 policies</a> and <a class="reference internal" href="#iv-ino-lblk-32-policies">IV_INO_LBLK_32 policies</a>, 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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
</section>
</section>
<section id="direct-i-o-support">
<h2>Direct I/O support<a class="headerlink" href="#direct-i-o-support" title="Link to this heading">¶</a></h2>
<p>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):</p>
<ul class="simple">
<li><p>The file must be using inline encryption.  Usually this means that
the filesystem must be mounted with <code class="docutils literal notranslate"><span class="pre">-o</span> <span class="pre">inlinecrypt</span></code> and inline
encryption hardware must be present.  However, a software fallback
is also available.  For details, see <a class="reference internal" href="#inline-encryption-support">Inline encryption support</a>.</p></li>
<li><p>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.</p></li>
</ul>
<p>If either of the above conditions is not met, then direct I/O on the
encrypted file will fall back to buffered I/O.</p>
</section>
<section id="implementation-details">
<h2>Implementation details<a class="headerlink" href="#implementation-details" title="Link to this heading">¶</a></h2>
<section id="encryption-context">
<h3>Encryption context<a class="headerlink" href="#encryption-context" title="Link to this heading">¶</a></h3>
<p>An encryption policy is represented on-disk by
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_context_v1</span></code> or <code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_context_v2</span></code>.  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 <em>not</em> be
exposed by the xattr-related system calls such as <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">getxattr()</span></code> and
<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">setxattr()</span></code> 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:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>#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];
};
</pre></div>
</div>
<p>The context structs contain the same information as the corresponding
policy structs (see <a class="reference internal" href="#setting-an-encryption-policy">Setting an encryption policy</a>), 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 <a class="reference internal" href="#per-file-encryption-keys">Per-file encryption
keys</a> and <a class="reference internal" href="#direct-key-policies">DIRECT_KEY policies</a>.</p>
</section>
<section id="data-path-changes">
<h3>Data path changes<a class="headerlink" href="#data-path-changes" title="Link to this heading">¶</a></h3>
<p>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.</p>
<p>When inline encryption isn’t used, filesystems must encrypt/decrypt
the file contents themselves, as described below:</p>
<p>For the read path (-&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">read_folio()</span></code>) 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.</p>
<p>For the write path (-&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">writepages()</span></code>) 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.</p>
</section>
<section id="filename-hashing-and-encoding">
<h3>Filename hashing and encoding<a class="headerlink" href="#filename-hashing-and-encoding" title="Link to this heading">¶</a></h3>
<p>Modern filesystems accelerate directory lookups by using indexed
directories.  An indexed directory is organized as a tree keyed by
filename hashes.  When a -&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">lookup()</span></code> is requested, the filesystem
normally hashes the filename being looked up so that it can quickly
find the corresponding directory entry, if any.</p>
<p>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 -&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">lookup()</span></code> with the key, the filesystem just encrypts
the user-supplied name to get the ciphertext.</p>
<p>Lookups without the key are more complicated.  The raw ciphertext may
contain the <code class="docutils literal notranslate"><span class="pre">\0</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code> characters, which are illegal in
filenames.  Therefore, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">readdir()</span></code> must base64url-encode the ciphertext
for presentation.  For most filenames, this works fine; on -&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">lookup()</span></code>,
the filesystem just base64url-decodes the user-supplied name to get
back to the raw ciphertext.</p>
<p>However, for very long filenames, base64url encoding would cause the
filename length to exceed NAME_MAX.  To prevent this, <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">readdir()</span></code>
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 -&gt;<code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">lookup()</span></code> back to a particular directory entry
that was previously listed by <code class="xref c c-func broken_xref docutils literal notranslate"><span class="pre">readdir()</span></code>.  See
<code class="xref c c-struct broken_xref docutils literal notranslate"><span class="pre">struct</span> <span class="pre">fscrypt_nokey_name</span></code> in the source for more details.</p>
<p>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
<code class="docutils literal notranslate"><span class="pre">rm</span> <span class="pre">-r</span></code> work as expected on encrypted directories.</p>
</section>
</section>
<section id="tests">
<h2>Tests<a class="headerlink" href="#tests" title="Link to this heading">¶</a></h2>
<p>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 <a class="reference external" href="https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md">kvm-xfstests</a>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>kvm-xfstests -c ext4,f2fs -g encrypt
kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
</pre></div>
</div>
<p>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:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>kvm-xfstests -c ubifs -g encrypt
</pre></div>
</div>
<p>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.</p>
<p>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:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
</pre></div>
</div>
<p>Because this runs many more tests than “-g encrypt” does, it takes
much longer to run; so also consider using <a class="reference external" href="https://github.com/tytso/xfstests-bld/blob/master/Documentation/gce-xfstests.md">gce-xfstests</a>
instead of kvm-xfstests:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
</pre></div>
</div>
</section>
</section>


          </div>
          
        </div>
      </div>
    <div class="clearer"></div>
  </div>
    <div class="footer">
      &#169;The kernel development community.
      
      |
      Powered by <a href="https://www.sphinx-doc.org/">Sphinx 8.1.3</a>
      &amp; <a href="https://alabaster.readthedocs.io">Alabaster 0.7.16</a>
      
      |
      <a href="../_sources/filesystems/fscrypt.rst.txt"
          rel="nofollow">Page source</a>
    </div>

    

    
  </body>
</html>

Filemanager

Name Type Size Permission Actions
caching Folder 0755
ext4 Folder 0755
fuse Folder 0755
iomap Folder 0755
nfs Folder 0755
smb Folder 0755
spufs Folder 0755
xfs Folder 0755
9p.html File 24.15 KB 0644
adfs.html File 13.15 KB 0644
affs.html File 18.5 KB 0644
afs.html File 19.14 KB 0644
api-summary.html File 831.83 KB 0644
autofs-mount-control.html File 32.3 KB 0644
autofs.html File 38.96 KB 0644
automount-support.html File 12.79 KB 0644
befs.html File 14.41 KB 0644
bfs.html File 10.72 KB 0644
btrfs.html File 9.7 KB 0644
buffer.html File 48.88 KB 0644
ceph.html File 18.87 KB 0644
coda.html File 65.97 KB 0644
configfs.html File 36.14 KB 0644
cramfs.html File 14.95 KB 0644
dax.html File 25.37 KB 0644
debugfs.html File 21.71 KB 0644
devpts.html File 10.61 KB 0644
directory-locking.html File 23.11 KB 0644
dlmfs.html File 14.28 KB 0644
dnotify.html File 12.09 KB 0644
ecryptfs.html File 11.96 KB 0644
efivarfs.html File 10 KB 0644
erofs.html File 29.42 KB 0644
ext2.html File 32.92 KB 0644
ext3.html File 8.29 KB 0644
f2fs.html File 67.87 KB 0644
fiemap.html File 23.32 KB 0644
files.html File 16.52 KB 0644
fscrypt.html File 107.9 KB 0644
fsverity.html File 64.53 KB 0644
gfs2-glocks.html File 21.71 KB 0644
gfs2-uevents.html File 12.88 KB 0644
gfs2.html File 10.38 KB 0644
hfs.html File 12.31 KB 0644
hfsplus.html File 10.28 KB 0644
hpfs.html File 26.83 KB 0644
idmappings.html File 74.42 KB 0644
index.html File 68.19 KB 0644
inotify.html File 12.35 KB 0644
isofs.html File 12.17 KB 0644
journalling.html File 115.17 KB 0644
locking.html File 52.92 KB 0644
locks.html File 11.91 KB 0644
mount_api.html File 49.94 KB 0644
multigrain-ts.html File 15 KB 0644
netfs_library.html File 86.81 KB 0644
nilfs2.html File 22.21 KB 0644
ntfs3.html File 13.64 KB 0644
ocfs2-online-filecheck.html File 13.13 KB 0644
ocfs2.html File 15.76 KB 0644
omfs.html File 13.12 KB 0644
orangefs.html File 35.89 KB 0644
overlayfs.html File 54.83 KB 0644
path-lookup.html File 123.09 KB 0644
porting.html File 94.09 KB 0644
proc.html File 140.32 KB 0644
qnx6.html File 16.36 KB 0644
quota.html File 12.12 KB 0644
ramfs-rootfs-initramfs.html File 27.94 KB 0644
relay.html File 40.38 KB 0644
resctrl.html File 93.99 KB 0644
romfs.html File 18.06 KB 0644
seq_file.html File 36.49 KB 0644
sharedsubtree.html File 46.25 KB 0644
splice.html File 79.36 KB 0644
squashfs.html File 24.34 KB 0644
sysfs.html File 29.32 KB 0644
tmpfs.html File 22.95 KB 0644
ubifs-authentication.html File 33.04 KB 0644
ubifs.html File 15.06 KB 0644
udf.html File 12.11 KB 0644
vfat.html File 26.07 KB 0644
vfs.html File 167.26 KB 0644
virtiofs.html File 12.16 KB 0644
zonefs.html File 35.71 KB 0644
Filemanager