ext4 crypto: add padding to filenames before encrypting

This obscures the length of the filenames, to decrease the amount of
information leakage.  By default, we pad the filenames to the next 4
byte boundaries.  This costs nothing, since the directory entries are
aligned to 4 byte boundaries anyway.  Filenames can also be padded to
8, 16, or 32 bytes, which will consume more directory space.

Change-Id: Ibb7a0fb76d2c48e2061240a709358ff40b14f322
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
diff --git a/fs/ext4/crypto_policy.c b/fs/ext4/crypto_policy.c
index 30eaf9e..a6d6291 100644
--- a/fs/ext4/crypto_policy.c
+++ b/fs/ext4/crypto_policy.c
@@ -37,6 +37,8 @@
 		return 0;
 	return (memcmp(ctx.master_key_descriptor, policy->master_key_descriptor,
 			EXT4_KEY_DESCRIPTOR_SIZE) == 0 &&
+		(ctx.flags ==
+		 policy->flags) &&
 		(ctx.contents_encryption_mode ==
 		 policy->contents_encryption_mode) &&
 		(ctx.filenames_encryption_mode ==
@@ -56,25 +58,25 @@
 		printk(KERN_WARNING
 		       "%s: Invalid contents encryption mode %d\n", __func__,
 			policy->contents_encryption_mode);
-		res = -EINVAL;
-		goto out;
+		return -EINVAL;
 	}
 	if (!ext4_valid_filenames_enc_mode(policy->filenames_encryption_mode)) {
 		printk(KERN_WARNING
 		       "%s: Invalid filenames encryption mode %d\n", __func__,
 			policy->filenames_encryption_mode);
-		res = -EINVAL;
-		goto out;
+		return -EINVAL;
 	}
+	if (policy->flags & ~EXT4_POLICY_FLAGS_VALID)
+		return -EINVAL;
 	ctx.contents_encryption_mode = policy->contents_encryption_mode;
 	ctx.filenames_encryption_mode = policy->filenames_encryption_mode;
+	ctx.flags = policy->flags;
 	BUILD_BUG_ON(sizeof(ctx.nonce) != EXT4_KEY_DERIVATION_NONCE_SIZE);
 	get_random_bytes(ctx.nonce, EXT4_KEY_DERIVATION_NONCE_SIZE);
 
 	res = ext4_xattr_set(inode, EXT4_XATTR_INDEX_ENCRYPTION,
 			     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, &ctx,
 			     sizeof(ctx), 0);
-out:
 	if (!res)
 		ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
 	return res;
@@ -115,6 +117,7 @@
 	policy->version = 0;
 	policy->contents_encryption_mode = ctx.contents_encryption_mode;
 	policy->filenames_encryption_mode = ctx.filenames_encryption_mode;
+	policy->flags = ctx.flags;
 	memcpy(&policy->master_key_descriptor, ctx.master_key_descriptor,
 	       EXT4_KEY_DESCRIPTOR_SIZE);
 	return 0;
@@ -176,6 +179,7 @@
 				EXT4_ENCRYPTION_MODE_AES_256_XTS;
 			ctx.filenames_encryption_mode =
 				EXT4_ENCRYPTION_MODE_AES_256_CTS;
+			ctx.flags = 0;
 			memset(ctx.master_key_descriptor, 0x42,
 			       EXT4_KEY_DESCRIPTOR_SIZE);
 			res = 0;