fscrypt-crypt-util: fix maximum IV size
[xfstests-dev.git] / src / fscrypt-crypt-util.c
index 81574a551e687204bb640f75fe607e6afe364a5f..03cc3c4a12997734195a455c1bfd2ba249525c5c 100644 (file)
  *
  * All algorithms are implemented in portable C code to avoid depending on
  * libcrypto (OpenSSL), and because some fscrypt-supported algorithms aren't
- * available in libcrypto anyway (e.g. Adiantum).  For simplicity, all crypto
- * code here tries to follow the mathematical definitions directly, without
- * optimizing for performance or worrying about following security best
- * practices such as mitigating side-channel attacks.  So, only use this program
- * for testing!
+ * available in libcrypto anyway (e.g. Adiantum), or are only supported in
+ * recent versions (e.g. HKDF-SHA512).  For simplicity, all crypto code here
+ * tries to follow the mathematical definitions directly, without optimizing for
+ * performance or worrying about following security best practices such as
+ * mitigating side-channel attacks.  So, only use this program for testing!
  */
 
 #include <asm/byteorder.h>
@@ -26,6 +26,7 @@
 #include <linux/types.h>
 #include <stdarg.h>
 #include <stdbool.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -58,13 +59,28 @@ static void usage(FILE *fp)
 "WARNING: this program is only meant for testing, not for \"real\" use!\n"
 "\n"
 "Options:\n"
+"  --block-number=BNUM         Starting block number for IV generation.\n"
+"                                Default: 0\n"
 "  --block-size=BLOCK_SIZE     Encrypt each BLOCK_SIZE bytes independently.\n"
 "                                Default: 4096 bytes\n"
 "  --decrypt                   Decrypt instead of encrypt\n"
 "  --file-nonce=NONCE          File's nonce as a 32-character hex string\n"
+"  --fs-uuid=UUID              The filesystem UUID as a 32-character hex string.\n"
+"                                Required for --iv-ino-lblk-32 and\n"
+"                                --iv-ino-lblk-64; otherwise is unused.\n"
 "  --help                      Show this help\n"
-"  --kdf=KDF                   Key derivation function to use: AES-128-ECB\n"
-"                                or none.  Default: none\n"
+"  --inode-number=INUM         The file's inode number.  Required for\n"
+"                                --iv-ino-lblk-32 and --iv-ino-lblk-64;\n"
+"                                otherwise is unused.\n"
+"  --iv-ino-lblk-32            Similar to --iv-ino-lblk-64, but selects the\n"
+"                                32-bit variant.\n"
+"  --iv-ino-lblk-64            Use the format where the IVs include the inode\n"
+"                                number and the same key is shared across files.\n"
+"                                Requires --kdf=HKDF-SHA512, --fs-uuid,\n"
+"                                --inode-number, and --mode-num.\n"
+"  --kdf=KDF                   Key derivation function to use: AES-128-ECB,\n"
+"                                HKDF-SHA512, or none.  Default: none\n"
+"  --mode-num=NUM              Derive per-mode key using mode number NUM\n"
 "  --padding=PADDING           If last block is partial, zero-pad it to next\n"
 "                                PADDING-byte boundary.  Default: BLOCK_SIZE\n"
        , fp);
@@ -134,6 +150,16 @@ static inline u32 ror32(u32 v, int n)
        return (v >> n) | (v << (32 - n));
 }
 
+static inline u64 rol64(u64 v, int n)
+{
+       return (v << n) | (v >> (64 - n));
+}
+
+static inline u64 ror64(u64 v, int n)
+{
+       return (v >> n) | (v << (64 - n));
+}
+
 static inline void xor(u8 *res, const u8 *a, const u8 *b, size_t count)
 {
        while (count--)
@@ -586,7 +612,7 @@ static void test_aes(void)
 #endif /* ENABLE_ALG_TESTS */
 
 /*----------------------------------------------------------------------------*
- *                                  SHA-256                                   *
+ *                            SHA-512 and SHA-256                             *
  *----------------------------------------------------------------------------*/
 
 /*
@@ -594,35 +620,104 @@ static void test_aes(void)
  *     https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2withchangenotice.pdf
  */
 
+#define SHA512_DIGEST_SIZE     64
+#define SHA512_BLOCK_SIZE      128
+
 #define SHA256_DIGEST_SIZE     32
 #define SHA256_BLOCK_SIZE      64
 
 #define Ch(x, y, z)    (((x) & (y)) ^ (~(x) & (z)))
 #define Maj(x, y, z)   (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
+
+#define Sigma512_0(x)  (ror64((x), 28) ^ ror64((x), 34) ^ ror64((x), 39))
+#define Sigma512_1(x)  (ror64((x), 14) ^ ror64((x), 18) ^ ror64((x), 41))
+#define sigma512_0(x)  (ror64((x),  1) ^ ror64((x),  8) ^ ((x) >> 7))
+#define sigma512_1(x)  (ror64((x), 19) ^ ror64((x), 61) ^ ((x) >> 6))
+
 #define Sigma256_0(x)  (ror32((x),  2) ^ ror32((x), 13) ^ ror32((x), 22))
 #define Sigma256_1(x)  (ror32((x),  6) ^ ror32((x), 11) ^ ror32((x), 25))
 #define sigma256_0(x)  (ror32((x),  7) ^ ror32((x), 18) ^ ((x) >>  3))
 #define sigma256_1(x)  (ror32((x), 17) ^ ror32((x), 19) ^ ((x) >> 10))
 
-static const u32 sha256_iv[8] = {
-       0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,
-       0x1f83d9ab, 0x5be0cd19,
+static const u64 sha512_iv[8] = {
+       0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b,
+       0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f,
+       0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
 };
 
-static const u32 sha256_round_constants[64] = {
-       0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
-       0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
-       0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
-       0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
-       0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
-       0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
-       0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
-       0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
-       0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
-       0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
-       0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+static const u64 sha512_round_constants[80] = {
+       0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f,
+       0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019,
+       0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242,
+       0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
+       0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
+       0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3,
+       0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275,
+       0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
+       0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f,
+       0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
+       0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc,
+       0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
+       0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6,
+       0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001,
+       0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
+       0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
+       0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99,
+       0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb,
+       0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc,
+       0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
+       0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915,
+       0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207,
+       0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba,
+       0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
+       0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
+       0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a,
+       0x5fcb6fab3ad6faec, 0x6c44198c4a475817,
 };
 
+/* Compute the SHA-512 digest of the given buffer */
+static void sha512(const u8 *in, size_t inlen, u8 out[SHA512_DIGEST_SIZE])
+{
+       const size_t msglen = ROUND_UP(inlen + 17, SHA512_BLOCK_SIZE);
+       u8 * const msg = xmalloc(msglen);
+       u64 H[8];
+       int i;
+
+       /* super naive way of handling the padding */
+       memcpy(msg, in, inlen);
+       memset(&msg[inlen], 0, msglen - inlen);
+       msg[inlen] = 0x80;
+       put_unaligned_be64((u64)inlen * 8, &msg[msglen - sizeof(__be64)]);
+       in = msg;
+
+       memcpy(H, sha512_iv, sizeof(H));
+       do {
+               u64 a = H[0], b = H[1], c = H[2], d = H[3],
+                   e = H[4], f = H[5], g = H[6], h = H[7];
+               u64 W[80];
+
+               for (i = 0; i < 16; i++)
+                       W[i] = get_unaligned_be64(&in[i * sizeof(__be64)]);
+               for (; i < ARRAY_SIZE(W); i++)
+                       W[i] = sigma512_1(W[i - 2]) + W[i - 7] +
+                              sigma512_0(W[i - 15]) + W[i - 16];
+               for (i = 0; i < ARRAY_SIZE(W); i++) {
+                       u64 T1 = h + Sigma512_1(e) + Ch(e, f, g) +
+                                sha512_round_constants[i] + W[i];
+                       u64 T2 = Sigma512_0(a) + Maj(a, b, c);
+
+                       h = g; g = f; f = e; e = d + T1;
+                       d = c; c = b; b = a; a = T1 + T2;
+               }
+               H[0] += a; H[1] += b; H[2] += c; H[3] += d;
+               H[4] += e; H[5] += f; H[6] += g; H[7] += h;
+       } while ((in += SHA512_BLOCK_SIZE) != &msg[msglen]);
+
+       for (i = 0; i < ARRAY_SIZE(H); i++)
+               put_unaligned_be64(H[i], &out[i * sizeof(__be64)]);
+       free(msg);
+}
+
 /* Compute the SHA-256 digest of the given buffer */
 static void sha256(const u8 *in, size_t inlen, u8 out[SHA256_DIGEST_SIZE])
 {
@@ -638,7 +733,8 @@ static void sha256(const u8 *in, size_t inlen, u8 out[SHA256_DIGEST_SIZE])
        put_unaligned_be64((u64)inlen * 8, &msg[msglen - sizeof(__be64)]);
        in = msg;
 
-       memcpy(H, sha256_iv, sizeof(H));
+       for (i = 0; i < ARRAY_SIZE(H); i++)
+               H[i] = (u32)(sha512_iv[i] >> 32);
        do {
                u32 a = H[0], b = H[1], c = H[2], d = H[3],
                    e = H[4], f = H[5], g = H[6], h = H[7];
@@ -651,7 +747,7 @@ static void sha256(const u8 *in, size_t inlen, u8 out[SHA256_DIGEST_SIZE])
                               sigma256_0(W[i - 15]) + W[i - 16];
                for (i = 0; i < ARRAY_SIZE(W); i++) {
                        u32 T1 = h + Sigma256_1(e) + Ch(e, f, g) +
-                                sha256_round_constants[i] + W[i];
+                                (u32)(sha512_round_constants[i] >> 32) + W[i];
                        u32 T2 = Sigma256_0(a) + Maj(a, b, c);
 
                        h = g; g = f; f = e; e = d + T1;
@@ -674,8 +770,8 @@ static void test_sha2(void)
 
        while (num_tests--) {
                u8 in[4096];
-               u8 digest[SHA256_DIGEST_SIZE];
-               u8 ref_digest[SHA256_DIGEST_SIZE];
+               u8 digest[SHA512_DIGEST_SIZE];
+               u8 ref_digest[SHA512_DIGEST_SIZE];
                const size_t inlen = rand() % (1 + sizeof(in));
 
                rand_bytes(in, inlen);
@@ -683,6 +779,124 @@ static void test_sha2(void)
                sha256(in, inlen, digest);
                SHA256(in, inlen, ref_digest);
                ASSERT(memcmp(digest, ref_digest, SHA256_DIGEST_SIZE) == 0);
+
+               sha512(in, inlen, digest);
+               SHA512(in, inlen, ref_digest);
+               ASSERT(memcmp(digest, ref_digest, SHA512_DIGEST_SIZE) == 0);
+       }
+}
+#endif /* ENABLE_ALG_TESTS */
+
+/*----------------------------------------------------------------------------*
+ *                            HKDF implementation                             *
+ *----------------------------------------------------------------------------*/
+
+static void hmac_sha512(const u8 *key, size_t keylen, const u8 *msg,
+                       size_t msglen, u8 mac[SHA512_DIGEST_SIZE])
+{
+       u8 *ibuf = xmalloc(SHA512_BLOCK_SIZE + msglen);
+       u8 obuf[SHA512_BLOCK_SIZE + SHA512_DIGEST_SIZE];
+
+       ASSERT(keylen <= SHA512_BLOCK_SIZE); /* keylen > bs not implemented */
+
+       memset(ibuf, 0x36, SHA512_BLOCK_SIZE);
+       xor(ibuf, ibuf, key, keylen);
+       memcpy(&ibuf[SHA512_BLOCK_SIZE], msg, msglen);
+
+       memset(obuf, 0x5c, SHA512_BLOCK_SIZE);
+       xor(obuf, obuf, key, keylen);
+       sha512(ibuf, SHA512_BLOCK_SIZE + msglen, &obuf[SHA512_BLOCK_SIZE]);
+       sha512(obuf, sizeof(obuf), mac);
+
+       free(ibuf);
+}
+
+static void hkdf_sha512(const u8 *ikm, size_t ikmlen,
+                       const u8 *salt, size_t saltlen,
+                       const u8 *info, size_t infolen,
+                       u8 *output, size_t outlen)
+{
+       static const u8 default_salt[SHA512_DIGEST_SIZE];
+       u8 prk[SHA512_DIGEST_SIZE]; /* pseudorandom key */
+       u8 *buf = xmalloc(1 + infolen + SHA512_DIGEST_SIZE);
+       u8 counter = 1;
+       size_t i;
+
+       if (saltlen == 0) {
+               salt = default_salt;
+               saltlen = sizeof(default_salt);
+       }
+
+       /* HKDF-Extract */
+       ASSERT(ikmlen > 0);
+       hmac_sha512(salt, saltlen, ikm, ikmlen, prk);
+
+       /* HKDF-Expand */
+       for (i = 0; i < outlen; i += SHA512_DIGEST_SIZE) {
+               u8 *p = buf;
+               u8 tmp[SHA512_DIGEST_SIZE];
+
+               ASSERT(counter != 0);
+               if (i > 0) {
+                       memcpy(p, &output[i - SHA512_DIGEST_SIZE],
+                              SHA512_DIGEST_SIZE);
+                       p += SHA512_DIGEST_SIZE;
+               }
+               memcpy(p, info, infolen);
+               p += infolen;
+               *p++ = counter++;
+               hmac_sha512(prk, sizeof(prk), buf, p - buf, tmp);
+               memcpy(&output[i], tmp, MIN(sizeof(tmp), outlen - i));
+       }
+       free(buf);
+}
+
+#ifdef ENABLE_ALG_TESTS
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+static void openssl_hkdf_sha512(const u8 *ikm, size_t ikmlen,
+                               const u8 *salt, size_t saltlen,
+                               const u8 *info, size_t infolen,
+                               u8 *output, size_t outlen)
+{
+       EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
+       size_t actual_outlen = outlen;
+
+       ASSERT(pctx != NULL);
+       ASSERT(EVP_PKEY_derive_init(pctx) > 0);
+       ASSERT(EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha512()) > 0);
+       ASSERT(EVP_PKEY_CTX_set1_hkdf_key(pctx, ikm, ikmlen) > 0);
+       ASSERT(EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltlen) > 0);
+       ASSERT(EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infolen) > 0);
+       ASSERT(EVP_PKEY_derive(pctx, output, &actual_outlen) > 0);
+       ASSERT(actual_outlen == outlen);
+       EVP_PKEY_CTX_free(pctx);
+}
+
+static void test_hkdf_sha512(void)
+{
+       unsigned long num_tests = NUM_ALG_TEST_ITERATIONS;
+
+       while (num_tests--) {
+               u8 ikm[SHA512_DIGEST_SIZE];
+               u8 salt[SHA512_DIGEST_SIZE];
+               u8 info[128];
+               u8 actual_output[512];
+               u8 expected_output[sizeof(actual_output)];
+               size_t ikmlen = 1 + (rand() % sizeof(ikm));
+               size_t saltlen = rand() % (1 + sizeof(salt));
+               size_t infolen = rand() % (1 + sizeof(info));
+               size_t outlen = rand() % (1 + sizeof(actual_output));
+
+               rand_bytes(ikm, ikmlen);
+               rand_bytes(salt, saltlen);
+               rand_bytes(info, infolen);
+
+               hkdf_sha512(ikm, ikmlen, salt, saltlen, info, infolen,
+                           actual_output, outlen);
+               openssl_hkdf_sha512(ikm, ikmlen, salt, saltlen, info, infolen,
+                                   expected_output, outlen);
+               ASSERT(memcmp(actual_output, expected_output, outlen) == 0);
        }
 }
 #endif /* ENABLE_ALG_TESTS */
@@ -1377,12 +1591,58 @@ static void test_adiantum(void)
 }
 #endif /* ENABLE_ALG_TESTS */
 
+/*----------------------------------------------------------------------------*
+ *                               SipHash-2-4                                  *
+ *----------------------------------------------------------------------------*/
+
+/*
+ * Reference: "SipHash: a fast short-input PRF"
+ *     https://cr.yp.to/siphash/siphash-20120918.pdf
+ */
+
+#define SIPROUND                                               \
+       do {                                                    \
+               v0 += v1;           v2 += v3;                   \
+               v1 = rol64(v1, 13); v3 = rol64(v3, 16);         \
+               v1 ^= v0;           v3 ^= v2;                   \
+               v0 = rol64(v0, 32);                             \
+               v2 += v1;           v0 += v3;                   \
+               v1 = rol64(v1, 17); v3 = rol64(v3, 21);         \
+               v1 ^= v2;           v3 ^= v0;                   \
+               v2 = rol64(v2, 32);                             \
+       } while (0)
+
+/* Compute the SipHash-2-4 of a 64-bit number when formatted as little endian */
+static u64 siphash_1u64(const u64 key[2], u64 data)
+{
+       u64 v0 = key[0] ^ 0x736f6d6570736575ULL;
+       u64 v1 = key[1] ^ 0x646f72616e646f6dULL;
+       u64 v2 = key[0] ^ 0x6c7967656e657261ULL;
+       u64 v3 = key[1] ^ 0x7465646279746573ULL;
+       u64 m[2] = {data, (u64)sizeof(data) << 56};
+       size_t i;
+
+       for (i = 0; i < ARRAY_SIZE(m); i++) {
+               v3 ^= m[i];
+               SIPROUND;
+               SIPROUND;
+               v0 ^= m[i];
+       }
+
+       v2 ^= 0xff;
+       for (i = 0; i < 4; i++)
+               SIPROUND;
+       return v0 ^ v1 ^ v2 ^ v3;
+}
+
 /*----------------------------------------------------------------------------*
  *                               Main program                                 *
  *----------------------------------------------------------------------------*/
 
 #define FILE_NONCE_SIZE                16
+#define UUID_SIZE              16
 #define MAX_KEY_SIZE           64
+#define MAX_IV_SIZE            ADIANTUM_IV_SIZE
 
 static const struct fscrypt_cipher {
        const char *name;
@@ -1435,16 +1695,34 @@ static const struct fscrypt_cipher *find_fscrypt_cipher(const char *name)
        return NULL;
 }
 
-struct fscrypt_iv {
-       union {
-               __le64 block_num;
-               u8 bytes[32];
+union fscrypt_iv {
+       /* usual IV format */
+       struct {
+               /* logical block number within the file */
+               __le64 block_number;
+
+               /* per-file nonce; only set in DIRECT_KEY mode */
+               u8 nonce[FILE_NONCE_SIZE];
+       };
+       /* IV format for IV_INO_LBLK_* modes */
+       struct {
+               /*
+                * IV_INO_LBLK_64: logical block number within the file
+                * IV_INO_LBLK_32: hashed inode number + logical block number
+                *                 within the file, mod 2^32
+                */
+               __le32 block_number32;
+
+               /* IV_INO_LBLK_64: inode number */
+               __le32 inode_number;
        };
+       /* Any extra bytes up to the algorithm's IV size must be zeroed */
+       u8 bytes[MAX_IV_SIZE];
 };
 
 static void crypt_loop(const struct fscrypt_cipher *cipher, const u8 *key,
-                      struct fscrypt_iv *iv, bool decrypting,
-                      size_t block_size, size_t padding)
+                      union fscrypt_iv *iv, bool decrypting,
+                      size_t block_size, size_t padding, bool is_bnum_32bit)
 {
        u8 *buf = xmalloc(block_size);
        size_t res;
@@ -1467,7 +1745,12 @@ static void crypt_loop(const struct fscrypt_cipher *cipher, const u8 *key,
 
                full_write(STDOUT_FILENO, buf, crypt_len);
 
-               iv->block_num = cpu_to_le64(le64_to_cpu(iv->block_num) + 1);
+               if (is_bnum_32bit)
+                       iv->block_number32 = cpu_to_le32(
+                                       le32_to_cpu(iv->block_number32) + 1);
+               else
+                       iv->block_number = cpu_to_le64(
+                                       le64_to_cpu(iv->block_number) + 1);
        }
        free(buf);
 }
@@ -1476,6 +1759,7 @@ static void crypt_loop(const struct fscrypt_cipher *cipher, const u8 *key,
 enum kdf_algorithm {
        KDF_NONE,
        KDF_AES_128_ECB,
+       KDF_HKDF_SHA512,
 };
 
 static enum kdf_algorithm parse_kdf_algorithm(const char *arg)
@@ -1484,62 +1768,191 @@ static enum kdf_algorithm parse_kdf_algorithm(const char *arg)
                return KDF_NONE;
        if (strcmp(arg, "AES-128-ECB") == 0)
                return KDF_AES_128_ECB;
+       if (strcmp(arg, "HKDF-SHA512") == 0)
+               return KDF_HKDF_SHA512;
        die("Unknown KDF: %s", arg);
 }
 
+static u8 parse_mode_number(const char *arg)
+{
+       char *tmp;
+       long num = strtol(arg, &tmp, 10);
+
+       if (num <= 0 || *tmp || (u8)num != num)
+               die("Invalid mode number: %s", arg);
+       return num;
+}
+
+struct key_and_iv_params {
+       u8 master_key[MAX_KEY_SIZE];
+       int master_key_size;
+       enum kdf_algorithm kdf;
+       u8 mode_num;
+       u8 file_nonce[FILE_NONCE_SIZE];
+       bool file_nonce_specified;
+       bool iv_ino_lblk_64;
+       bool iv_ino_lblk_32;
+       u64 block_number;
+       u64 inode_number;
+       u8 fs_uuid[UUID_SIZE];
+       bool fs_uuid_specified;
+};
+
+#define HKDF_CONTEXT_KEY_IDENTIFIER    1
+#define HKDF_CONTEXT_PER_FILE_ENC_KEY  2
+#define HKDF_CONTEXT_DIRECT_KEY                3
+#define HKDF_CONTEXT_IV_INO_LBLK_64_KEY        4
+#define HKDF_CONTEXT_DIRHASH_KEY       5
+#define HKDF_CONTEXT_IV_INO_LBLK_32_KEY        6
+#define HKDF_CONTEXT_INODE_HASH_KEY    7
+
+/* Hash the file's inode number using SipHash keyed by a derived key */
+static u32 hash_inode_number(const struct key_and_iv_params *params)
+{
+       u8 info[9] = "fscrypt";
+       union {
+               u64 words[2];
+               u8 bytes[16];
+       } hash_key;
+
+       info[8] = HKDF_CONTEXT_INODE_HASH_KEY;
+       hkdf_sha512(params->master_key, params->master_key_size,
+                   NULL, 0, info, sizeof(info),
+                   hash_key.bytes, sizeof(hash_key));
+
+       hash_key.words[0] = get_unaligned_le64(&hash_key.bytes[0]);
+       hash_key.words[1] = get_unaligned_le64(&hash_key.bytes[8]);
+
+       return (u32)siphash_1u64(hash_key.words, params->inode_number);
+}
+
 /*
  * Get the key and starting IV with which the encryption will actually be done.
- * If a KDF was specified, a subkey is derived from the master key and file
- * nonce.  Otherwise, the master key is used directly.
+ * If a KDF was specified, a subkey is derived from the master key and the mode
+ * number or file nonce.  Otherwise, the master key is used directly.
  */
-static void get_key_and_iv(const u8 *master_key, size_t master_key_size,
-                          enum kdf_algorithm kdf,
-                          const u8 nonce[FILE_NONCE_SIZE],
+static void get_key_and_iv(const struct key_and_iv_params *params,
                           u8 *real_key, size_t real_key_size,
-                          struct fscrypt_iv *iv)
+                          union fscrypt_iv *iv)
 {
+       bool file_nonce_in_iv = false;
        struct aes_key aes_key;
+       u8 info[8 + 1 + 1 + UUID_SIZE] = "fscrypt";
+       size_t infolen = 8;
        size_t i;
 
-       ASSERT(real_key_size <= master_key_size);
+       ASSERT(real_key_size <= params->master_key_size);
 
        memset(iv, 0, sizeof(*iv));
 
-       switch (kdf) {
+       /* Overridden later for iv_ino_lblk_{64,32} */
+       iv->block_number = cpu_to_le64(params->block_number);
+
+       if (params->iv_ino_lblk_64 || params->iv_ino_lblk_32) {
+               const char *opt = params->iv_ino_lblk_64 ? "--iv-ino-lblk-64" :
+                                                          "--iv-ino-lblk-32";
+               if (params->iv_ino_lblk_64 && params->iv_ino_lblk_32)
+                       die("--iv-ino-lblk-64 and --iv-ino-lblk-32 are mutually exclusive");
+               if (params->kdf != KDF_HKDF_SHA512)
+                       die("%s requires --kdf=HKDF-SHA512", opt);
+               if (!params->fs_uuid_specified)
+                       die("%s requires --fs-uuid", opt);
+               if (params->inode_number == 0)
+                       die("%s requires --inode-number", opt);
+               if (params->mode_num == 0)
+                       die("%s requires --mode-num", opt);
+               if (params->block_number > UINT32_MAX)
+                       die("%s can't use --block-number > UINT32_MAX", opt);
+               if (params->inode_number > UINT32_MAX)
+                       die("%s can't use --inode-number > UINT32_MAX", opt);
+       }
+
+       switch (params->kdf) {
        case KDF_NONE:
-               memcpy(real_key, master_key, real_key_size);
-               if (nonce != NULL)
-                       memcpy(&iv->bytes[8], nonce, FILE_NONCE_SIZE);
+               if (params->mode_num != 0)
+                       die("--mode-num isn't supported with --kdf=none");
+               memcpy(real_key, params->master_key, real_key_size);
+               file_nonce_in_iv = true;
                break;
        case KDF_AES_128_ECB:
-               if (nonce == NULL)
+               if (!params->file_nonce_specified)
                        die("--file-nonce is required with --kdf=AES-128-ECB");
+               if (params->mode_num != 0)
+                       die("--mode-num isn't supported with --kdf=AES-128-ECB");
                STATIC_ASSERT(FILE_NONCE_SIZE == AES_128_KEY_SIZE);
                ASSERT(real_key_size % AES_BLOCK_SIZE == 0);
-               aes_setkey(&aes_key, nonce, AES_128_KEY_SIZE);
+               aes_setkey(&aes_key, params->file_nonce, AES_128_KEY_SIZE);
                for (i = 0; i < real_key_size; i += AES_BLOCK_SIZE)
-                       aes_encrypt(&aes_key, &master_key[i], &real_key[i]);
+                       aes_encrypt(&aes_key, &params->master_key[i],
+                                   &real_key[i]);
+               break;
+       case KDF_HKDF_SHA512:
+               if (params->iv_ino_lblk_64) {
+                       info[infolen++] = HKDF_CONTEXT_IV_INO_LBLK_64_KEY;
+                       info[infolen++] = params->mode_num;
+                       memcpy(&info[infolen], params->fs_uuid, UUID_SIZE);
+                       infolen += UUID_SIZE;
+                       iv->block_number32 = cpu_to_le32(params->block_number);
+                       iv->inode_number = cpu_to_le32(params->inode_number);
+               } else if (params->iv_ino_lblk_32) {
+                       info[infolen++] = HKDF_CONTEXT_IV_INO_LBLK_32_KEY;
+                       info[infolen++] = params->mode_num;
+                       memcpy(&info[infolen], params->fs_uuid, UUID_SIZE);
+                       infolen += UUID_SIZE;
+                       iv->block_number32 =
+                               cpu_to_le32(hash_inode_number(params) +
+                                           params->block_number);
+                       iv->inode_number = 0;
+               } else if (params->mode_num != 0) {
+                       info[infolen++] = HKDF_CONTEXT_DIRECT_KEY;
+                       info[infolen++] = params->mode_num;
+                       file_nonce_in_iv = true;
+               } else if (params->file_nonce_specified) {
+                       info[infolen++] = HKDF_CONTEXT_PER_FILE_ENC_KEY;
+                       memcpy(&info[infolen], params->file_nonce,
+                              FILE_NONCE_SIZE);
+                       infolen += FILE_NONCE_SIZE;
+               } else {
+                       die("With --kdf=HKDF-SHA512, at least one of --file-nonce and --mode-num must be specified");
+               }
+               hkdf_sha512(params->master_key, params->master_key_size,
+                           NULL, 0, info, infolen, real_key, real_key_size);
                break;
        default:
                ASSERT(0);
        }
+
+       if (file_nonce_in_iv && params->file_nonce_specified)
+               memcpy(iv->nonce, params->file_nonce, FILE_NONCE_SIZE);
 }
 
 enum {
+       OPT_BLOCK_NUMBER,
        OPT_BLOCK_SIZE,
        OPT_DECRYPT,
        OPT_FILE_NONCE,
+       OPT_FS_UUID,
        OPT_HELP,
+       OPT_INODE_NUMBER,
+       OPT_IV_INO_LBLK_32,
+       OPT_IV_INO_LBLK_64,
        OPT_KDF,
+       OPT_MODE_NUM,
        OPT_PADDING,
 };
 
 static const struct option longopts[] = {
+       { "block-number",    required_argument, NULL, OPT_BLOCK_NUMBER },
        { "block-size",      required_argument, NULL, OPT_BLOCK_SIZE },
        { "decrypt",         no_argument,       NULL, OPT_DECRYPT },
        { "file-nonce",      required_argument, NULL, OPT_FILE_NONCE },
+       { "fs-uuid",         required_argument, NULL, OPT_FS_UUID },
        { "help",            no_argument,       NULL, OPT_HELP },
+       { "inode-number",    required_argument, NULL, OPT_INODE_NUMBER },
+       { "iv-ino-lblk-32",  no_argument,       NULL, OPT_IV_INO_LBLK_32 },
+       { "iv-ino-lblk-64",  no_argument,       NULL, OPT_IV_INO_LBLK_64 },
        { "kdf",             required_argument, NULL, OPT_KDF },
+       { "mode-num",        required_argument, NULL, OPT_MODE_NUM },
        { "padding",         required_argument, NULL, OPT_PADDING },
        { NULL, 0, NULL, 0 },
 };
@@ -1548,23 +1961,22 @@ int main(int argc, char *argv[])
 {
        size_t block_size = 4096;
        bool decrypting = false;
-       u8 _file_nonce[FILE_NONCE_SIZE];
-       u8 *file_nonce = NULL;
-       enum kdf_algorithm kdf = KDF_NONE;
+       struct key_and_iv_params params;
        size_t padding = 0;
        const struct fscrypt_cipher *cipher;
-       u8 master_key[MAX_KEY_SIZE];
-       int master_key_size;
        u8 real_key[MAX_KEY_SIZE];
-       struct fscrypt_iv iv;
+       union fscrypt_iv iv;
        char *tmp;
        int c;
 
+       memset(&params, 0, sizeof(params));
+
        aes_init();
 
 #ifdef ENABLE_ALG_TESTS
        test_aes();
        test_sha2();
+       test_hkdf_sha512();
        test_aes_256_xts();
        test_aes_256_cts_cbc();
        test_adiantum();
@@ -1572,25 +1984,53 @@ int main(int argc, char *argv[])
 
        while ((c = getopt_long(argc, argv, "", longopts, NULL)) != -1) {
                switch (c) {
+               case OPT_BLOCK_NUMBER:
+                       errno = 0;
+                       params.block_number = strtoull(optarg, &tmp, 10);
+                       if (*tmp || errno)
+                               die("Invalid block number: %s", optarg);
+                       break;
                case OPT_BLOCK_SIZE:
+                       errno = 0;
                        block_size = strtoul(optarg, &tmp, 10);
-                       if (block_size <= 0 || *tmp)
+                       if (block_size <= 0 || *tmp || errno)
                                die("Invalid block size: %s", optarg);
                        break;
                case OPT_DECRYPT:
                        decrypting = true;
                        break;
                case OPT_FILE_NONCE:
-                       if (hex2bin(optarg, _file_nonce, FILE_NONCE_SIZE) !=
-                           FILE_NONCE_SIZE)
+                       if (hex2bin(optarg, params.file_nonce, FILE_NONCE_SIZE)
+                           != FILE_NONCE_SIZE)
                                die("Invalid file nonce: %s", optarg);
-                       file_nonce = _file_nonce;
+                       params.file_nonce_specified = true;
+                       break;
+               case OPT_FS_UUID:
+                       if (hex2bin(optarg, params.fs_uuid, UUID_SIZE)
+                           != UUID_SIZE)
+                               die("Invalid filesystem UUID: %s", optarg);
+                       params.fs_uuid_specified = true;
                        break;
                case OPT_HELP:
                        usage(stdout);
                        return 0;
+               case OPT_INODE_NUMBER:
+                       errno = 0;
+                       params.inode_number = strtoull(optarg, &tmp, 10);
+                       if (params.inode_number <= 0 || *tmp || errno)
+                               die("Invalid inode number: %s", optarg);
+                       break;
+               case OPT_IV_INO_LBLK_32:
+                       params.iv_ino_lblk_32 = true;
+                       break;
+               case OPT_IV_INO_LBLK_64:
+                       params.iv_ino_lblk_64 = true;
+                       break;
                case OPT_KDF:
-                       kdf = parse_kdf_algorithm(optarg);
+                       params.kdf = parse_kdf_algorithm(optarg);
+                       break;
+               case OPT_MODE_NUM:
+                       params.mode_num = parse_mode_number(optarg);
                        break;
                case OPT_PADDING:
                        padding = strtoul(optarg, &tmp, 10);
@@ -1619,15 +2059,16 @@ int main(int argc, char *argv[])
                die("Block size of %zu bytes is too small for cipher %s",
                    block_size, cipher->name);
 
-       master_key_size = hex2bin(argv[1], master_key, MAX_KEY_SIZE);
-       if (master_key_size < 0)
+       params.master_key_size = hex2bin(argv[1], params.master_key,
+                                        MAX_KEY_SIZE);
+       if (params.master_key_size < 0)
                die("Invalid master_key: %s", argv[1]);
-       if (master_key_size < cipher->keysize)
+       if (params.master_key_size < cipher->keysize)
                die("Master key is too short for cipher %s", cipher->name);
 
-       get_key_and_iv(master_key, master_key_size, kdf, file_nonce,
-                      real_key, cipher->keysize, &iv);
+       get_key_and_iv(&params, real_key, cipher->keysize, &iv);
 
-       crypt_loop(cipher, real_key, &iv, decrypting, block_size, padding);
+       crypt_loop(cipher, real_key, &iv, decrypting, block_size, padding,
+                  params.iv_ino_lblk_64 || params.iv_ino_lblk_32);
        return 0;
 }