[PATCH 02/12] common/encrypt: add btrfs to get_encryption_*nonce

Daniel Vacek <[email protected]> Fri, 24 Jul 2026 15:33:18 +0200
Newsgroups org.kernel.vger.linux-fscrypt,net.sourceforge.lists.linux-f2fs-devel,org.kernel.vger.fstests,org.kernel.vger.linux-btrfs,org.kernel.vger.linux-ext4,org.kernel.vger.linux-xfs
Message-ID <[email protected]>
From: Sweet Tea Dorminy <[email protected]>

Add the modes of getting the encryption nonces, either inode or extent,
to the various get_encryption_nonce functions. For now, no encrypt test
makes a file with more than one extent, so we can just grab the first
extent's nonce for the data nonce; when we write a bigger file test,
we'll need to change that.

v1:
 * adapt to the new on-disk format (btrfs-progs dump-tree changed).
   - use simple sed substitution to get the raw nonce

Signed-off-by: Sweet Tea Dorminy <[email protected]>
Signed-off-by: Daniel Vacek <[email protected]>
---
 common/encrypt | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/common/encrypt b/common/encrypt
index 8f664518..29293ea4 100644
--- a/common/encrypt
+++ b/common/encrypt
@@ -591,6 +591,16 @@ _get_encryption_file_nonce()
 				found = 0;
 			}'
 		;;
+	btrfs)
+		# Retrieve the fscrypt context for an inode as a hex string.
+		# btrfs prints these like:
+		#
+		#	item 21 key (258 FSCRYPT_INODE_CTX 0) itemoff 15081 itemsize 40
+		#		value: 020104000000000026845b8fc4d86191a06600879b25a852818ab722beec5fc403df968bf2e03af5
+		#
+		$BTRFS_UTIL_PROG inspect-internal dump-tree $device | \
+			sed -n "/key ($inode FSCRYPT_INODE_CTX 0)/{n;s/.*value: .*\([0-9a-f]\{32\}\)$/\1/p}"
+		;;
 	*)
 		_fail "_get_encryption_file_nonce() isn't implemented on $FSTYP"
 		;;
@@ -610,6 +620,16 @@ _get_encryption_data_nonce()
 	ext4|f2fs)
 		_get_encryption_file_nonce $device $inode
 		;;
+	btrfs)
+		# Retrieve the encryption IV of the first file extent in an inode as a hex
+		# string. btrfs prints the extent fscrypt context like:
+		#
+		#	item 22 key (258 FSCRYPT_CTX 0) itemoff 15047 itemsize 34
+		#		value: 010126845b8fc4d86191a06600879b25a852729c4e35b33e29d171a0c96b9eed33d9
+		#
+		$BTRFS_UTIL_PROG inspect-internal dump-tree $device | \
+			sed -n "/key ($inode FSCRYPT_CTX 0)/{n;s/.*value: .*\([0-9a-f]\{32\}\)$/\1/p}"
+		;;
 	*)
 		_fail "_get_encryption_data_nonce() isn't implemented on $FSTYP"
 		;;
@@ -632,6 +652,9 @@ _require_get_encryption_nonce_support()
 		# Otherwise the xattr is incorrectly parsed as v1.  But just let
 		# the test fail in that case, as it was an f2fs-tools bug...
 		;;
+	btrfs)
+		_require_command "$BTRFS_UTIL_PROG" btrfs
+		;;
 	*)
 		_notrun "_get_encryption_*nonce() isn't implemented on $FSTYP"
 		;;
-- 
2.53.0