common/encrypt: support verifying ciphertext of IV_INO_LBLK_64 policies
[xfstests-dev.git] / common / encrypt
1 ##/bin/bash
2 # SPDX-License-Identifier: GPL-2.0
3 # Copyright (c) 2016 Google, Inc.  All Rights Reserved.
4 #
5 # Functions for setting up and testing file encryption
6
7 #
8 # _require_scratch_encryption [-c CONTENTS_MODE] [-n FILENAMES_MODE]
9 #                             [-f POLICY_FLAGS] [-v POLICY_VERSION]
10 #
11 # Require encryption support on the scratch device.
12 #
13 # This checks for support for the default type of encryption policy (v1 with
14 # AES-256-XTS and AES-256-CTS).  Options can be specified to also require
15 # support for a different type of encryption policy.
16 #
17 _require_scratch_encryption()
18 {
19         _require_scratch
20
21         _require_xfs_io_command "set_encpolicy"
22
23         # The 'test_dummy_encryption' mount option interferes with trying to use
24         # encryption for real, even if we are just trying to get/set policies
25         # and never put any keys in the keyring.  So skip the real encryption
26         # tests if the 'test_dummy_encryption' mount option was specified.
27         _exclude_scratch_mount_option "test_dummy_encryption"
28
29         # Make a filesystem on the scratch device with the encryption feature
30         # enabled.  If this fails then probably the userspace tools (e.g.
31         # e2fsprogs or f2fs-tools) are too old to understand encryption.
32         if ! _scratch_mkfs_encrypted &>>$seqres.full; then
33                 _notrun "$FSTYP userspace tools do not support encryption"
34         fi
35
36         # Try to mount the filesystem.  If this fails then either the kernel
37         # isn't aware of encryption, or the mkfs options were not compatible
38         # with encryption (e.g. ext4 with block size != PAGE_SIZE).
39         if ! _try_scratch_mount &>>$seqres.full; then
40                 _notrun "kernel is unaware of $FSTYP encryption feature," \
41                         "or mkfs options are not compatible with encryption"
42         fi
43
44         # The kernel may be aware of encryption without supporting it.  For
45         # example, for ext4 this is the case with kernels configured with
46         # CONFIG_EXT4_FS_ENCRYPTION=n.  Detect support for encryption by trying
47         # to set an encryption policy.  (For ext4 we could instead check for the
48         # presence of /sys/fs/ext4/features/encryption, but this is broken on
49         # some older kernels and is ext4-specific anyway.)
50         mkdir $SCRATCH_MNT/tmpdir
51         if _set_encpolicy $SCRATCH_MNT/tmpdir 2>&1 >>$seqres.full | \
52                 egrep -q 'Inappropriate ioctl for device|Operation not supported'
53         then
54                 _notrun "kernel does not support $FSTYP encryption"
55         fi
56         rmdir $SCRATCH_MNT/tmpdir
57
58         # If required, check for support for the specific type of encryption
59         # policy required by the test.
60         if [ $# -ne 0 ]; then
61                 _require_encryption_policy_support $SCRATCH_MNT "$@"
62         fi
63
64         _scratch_unmount
65 }
66
67 _require_encryption_policy_support()
68 {
69         local mnt=$1
70         local dir=$mnt/tmpdir
71         local set_encpolicy_args=""
72         local policy_flags=0
73         local policy_version=1
74         local c
75
76         OPTIND=2
77         while getopts "c:n:f:v:" c; do
78                 case $c in
79                 c|n)
80                         set_encpolicy_args+=" -$c $OPTARG"
81                         ;;
82                 f)
83                         set_encpolicy_args+=" -$c $OPTARG"
84                         policy_flags=$OPTARG
85                         ;;
86                 v)
87                         set_encpolicy_args+=" -$c $OPTARG"
88                         policy_version=$OPTARG
89                         ;;
90                 *)
91                         _fail "Unrecognized option '$c'"
92                         ;;
93                 esac
94         done
95         set_encpolicy_args=${set_encpolicy_args# }
96
97         echo "Checking whether kernel supports encryption policy: $set_encpolicy_args" \
98                 >> $seqres.full
99
100         if (( policy_flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 )); then
101                 _scratch_unmount
102                 _scratch_mkfs_stable_inodes_encrypted &>> $seqres.full
103                 _scratch_mount
104         fi
105
106         mkdir $dir
107         if (( policy_version > 1 )); then
108                 _require_xfs_io_command "get_encpolicy" "-t"
109                 local output=$(_get_encpolicy $dir -t)
110                 if [ "$output" != "supported" ]; then
111                         if [ "$output" = "unsupported" ]; then
112                                 _notrun "kernel does not support $FSTYP encryption v2 API"
113                         fi
114                         _fail "Unexpected output from 'get_encpolicy -t': $output"
115                 fi
116                 # Both the kernel and xfs_io support v2 encryption policies, and
117                 # therefore also filesystem-level keys -- since that's the only
118                 # way to provide keys for v2 policies.
119                 local raw_key=$(_generate_raw_encryption_key)
120                 local keyspec=$(_add_enckey $mnt "$raw_key" | awk '{print $NF}')
121         else
122                 _require_command "$KEYCTL_PROG" keyctl
123                 _new_session_keyring
124                 local keyspec=$(_generate_session_encryption_key)
125         fi
126         if _set_encpolicy $dir $keyspec $set_encpolicy_args \
127                 2>&1 >>$seqres.full | egrep -q 'Invalid argument'; then
128                 _notrun "kernel does not support encryption policy: '$set_encpolicy_args'"
129         fi
130         # fscrypt allows setting policies with modes it knows about, even
131         # without kernel crypto API support.  E.g. a policy using Adiantum
132         # encryption can be set on a kernel without CONFIG_CRYPTO_ADIANTUM.
133         # But actually trying to use such an encrypted directory will fail.
134         # To reliably check for availability of both the contents and filenames
135         # encryption modes, try creating a nonempty file.
136         if ! echo foo > $dir/file; then
137                 _notrun "encryption policy '$set_encpolicy_args' is unusable; probably missing kernel crypto API support"
138         fi
139         if (( policy_version <= 1 )); then
140                 $KEYCTL_PROG clear @s
141         fi
142         rm -r $dir
143 }
144
145 _scratch_mkfs_encrypted()
146 {
147         case $FSTYP in
148         ext4|f2fs)
149                 _scratch_mkfs -O encrypt
150                 ;;
151         ubifs)
152                 # erase the UBI volume; reformated automatically on next mount
153                 $UBIUPDATEVOL_PROG ${SCRATCH_DEV} -t
154                 ;;
155         *)
156                 _notrun "No encryption support for $FSTYP"
157                 ;;
158         esac
159 }
160
161 _scratch_mkfs_sized_encrypted()
162 {
163         case $FSTYP in
164         ext4|f2fs)
165                 MKFS_OPTIONS="$MKFS_OPTIONS -O encrypt" _scratch_mkfs_sized $*
166                 ;;
167         *)
168                 _notrun "Filesystem $FSTYP not supported in _scratch_mkfs_sized_encrypted"
169                 ;;
170         esac
171 }
172
173 # Like _scratch_mkfs_encrypted(), but add -O stable_inodes if applicable for the
174 # filesystem type.  This is necessary for using encryption policies that include
175 # the inode number in the IVs, e.g. policies with the IV_INO_LBLK_64 flag set.
176 _scratch_mkfs_stable_inodes_encrypted()
177 {
178         case $FSTYP in
179         ext4)
180                 if ! _scratch_mkfs -O encrypt -O stable_inodes; then
181                         _notrun "-O stable_inodes is not supported"
182                 fi
183                 ;;
184         *)
185                 _scratch_mkfs_encrypted
186                 ;;
187         esac
188 }
189
190 # Give the invoking shell a new session keyring.  This makes any keys we add to
191 # the session keyring scoped to the lifetime of the test script.
192 _new_session_keyring()
193 {
194         $KEYCTL_PROG new_session >>$seqres.full
195 }
196
197 # Generate a key descriptor (16 character hex string)
198 _generate_key_descriptor()
199 {
200         local keydesc=""
201         local i
202         for ((i = 0; i < 8; i++)); do
203                 keydesc="${keydesc}$(printf "%02x" $(( $RANDOM % 256 )))"
204         done
205         echo $keydesc
206 }
207
208 # Generate a raw encryption key, but don't add it to any keyring yet.
209 _generate_raw_encryption_key()
210 {
211         local raw=""
212         local i
213         for ((i = 0; i < 64; i++)); do
214                 raw="${raw}\\x$(printf "%02x" $(( $RANDOM % 256 )))"
215         done
216         echo $raw
217 }
218
219 # Add the specified raw encryption key to the session keyring, using the
220 # specified key descriptor.
221 _add_session_encryption_key()
222 {
223         local keydesc=$1
224         local raw=$2
225
226         #
227         # Add the key to the session keyring.  The required structure is:
228         #
229         #       #define FS_MAX_KEY_SIZE 64
230         #       struct fscrypt_key {
231         #               u32 mode;
232         #               u8 raw[FS_MAX_KEY_SIZE];
233         #               u32 size;
234         #       } __packed;
235         #
236         # The kernel ignores 'mode' but requires that 'size' be 64.
237         #
238         # Keys are named $FSTYP:KEYDESC where KEYDESC is the 16-character key
239         # descriptor hex string.  Newer kernels (ext4 4.8 and later, f2fs 4.6
240         # and later) also allow the common key prefix "fscrypt:" in addition to
241         # their filesystem-specific key prefix ("ext4:", "f2fs:").  It would be
242         # nice to use the common key prefix, but for now use the filesystem-
243         # specific prefix to make it possible to test older kernels...
244         #
245         local big_endian=$(echo -ne '\x11' | od -tx2 | head -1 | \
246                            cut -f2 -d' ' | cut -c1 )
247         if (( big_endian )); then
248                 local mode='\x00\x00\x00\x00'
249                 local size='\x00\x00\x00\x40'
250         else
251                 local mode='\x00\x00\x00\x00'
252                 local size='\x40\x00\x00\x00'
253         fi
254         echo -n -e "${mode}${raw}${size}" |
255                 $KEYCTL_PROG padd logon $FSTYP:$keydesc @s >>$seqres.full
256 }
257
258 #
259 # Generate a random encryption key, add it to the session keyring, and print out
260 # the resulting key descriptor (example: "8bf798e1a494e1ec").  Requires the
261 # keyctl program.  It's assumed the caller has already set up a test-scoped
262 # session keyring using _new_session_keyring.
263 #
264 _generate_session_encryption_key()
265 {
266         local keydesc=$(_generate_key_descriptor)
267         local raw=$(_generate_raw_encryption_key)
268
269         _add_session_encryption_key $keydesc $raw
270
271         echo $keydesc
272 }
273
274 # Unlink an encryption key from the session keyring, given its key descriptor.
275 _unlink_session_encryption_key()
276 {
277         local keydesc=$1
278         local keyid=$($KEYCTL_PROG search @s logon $FSTYP:$keydesc)
279         $KEYCTL_PROG unlink $keyid >>$seqres.full
280 }
281
282 # Revoke an encryption key from the session keyring, given its key descriptor.
283 _revoke_session_encryption_key()
284 {
285         local keydesc=$1
286         local keyid=$($KEYCTL_PROG search @s logon $FSTYP:$keydesc)
287         $KEYCTL_PROG revoke $keyid >>$seqres.full
288 }
289
290 # Set an encryption policy on the specified directory.
291 _set_encpolicy()
292 {
293         local dir=$1
294         shift
295
296         $XFS_IO_PROG -c "set_encpolicy $*" "$dir"
297 }
298
299 _user_do_set_encpolicy()
300 {
301         local dir=$1
302         shift
303
304         _user_do "$XFS_IO_PROG -c \"set_encpolicy $*\" \"$dir\""
305 }
306
307 # Display the specified file or directory's encryption policy.
308 _get_encpolicy()
309 {
310         local file=$1
311         shift
312
313         $XFS_IO_PROG -c "get_encpolicy $*" "$file"
314 }
315
316 _user_do_get_encpolicy()
317 {
318         local file=$1
319         shift
320
321         _user_do "$XFS_IO_PROG -c \"get_encpolicy $*\" \"$file\""
322 }
323
324 # Add an encryption key to the given filesystem.
325 _add_enckey()
326 {
327         local mnt=$1
328         local raw_key=$2
329         shift 2
330
331         echo -ne "$raw_key" | $XFS_IO_PROG -c "add_enckey $*" "$mnt"
332 }
333
334 _user_do_add_enckey()
335 {
336         local mnt=$1
337         local raw_key=$2
338         shift 2
339
340         _user_do "echo -ne \"$raw_key\" | $XFS_IO_PROG -c \"add_enckey $*\" \"$mnt\""
341 }
342
343 # Remove the given encryption key from the given filesystem.
344 _rm_enckey()
345 {
346         local mnt=$1
347         local keyspec=$2
348         shift 2
349
350         $XFS_IO_PROG -c "rm_enckey $* $keyspec" "$mnt"
351 }
352
353 _user_do_rm_enckey()
354 {
355         local mnt=$1
356         local keyspec=$2
357         shift 2
358
359         _user_do "$XFS_IO_PROG -c \"rm_enckey $* $keyspec\" \"$mnt\""
360 }
361
362 # Get the status of the given encryption key on the given filesystem.
363 _enckey_status()
364 {
365         local mnt=$1
366         local keyspec=$2
367         shift 2
368
369         $XFS_IO_PROG -c "enckey_status $* $keyspec" "$mnt"
370 }
371
372 _user_do_enckey_status()
373 {
374         local mnt=$1
375         local keyspec=$2
376         shift 2
377
378         _user_do "$XFS_IO_PROG -c \"enckey_status $* $keyspec\" \"$mnt\""
379 }
380
381 # Retrieve the encryption nonce of the given inode as a hex string.  The nonce
382 # was randomly generated by the filesystem and isn't exposed directly to
383 # userspace.  But it can be read using the filesystem's debugging tools.
384 _get_encryption_nonce()
385 {
386         local device=$1
387         local inode=$2
388
389         case $FSTYP in
390         ext4)
391                 # Use debugfs to dump the special xattr named "c", which is the
392                 # file's fscrypt_context.  This produces a line like:
393                 #
394                 #       c (28) = 01 01 04 02 00 00 00 00 00 00 00 00 ef bd 18 76 5d f6 41 4e c0 a2 cd 5f 91 29 7e 12
395                 #
396                 # Then filter it to get just the 16-byte 'nonce' field at the end:
397                 #
398                 #       efbd18765df6414ec0a2cd5f91297e12
399                 #
400                 $DEBUGFS_PROG $device -R "ea_get <$inode> c" 2>>$seqres.full \
401                         | grep '^c ' | sed 's/^.*=//' | tr -d ' \n' | tail -c 32
402                 ;;
403         f2fs)
404                 # dump.f2fs prints the fscrypt_context like:
405                 #
406                 #       xattr: e_name_index:9 e_name:c e_name_len:1 e_value_size:28 e_value:
407                 #       format: 1
408                 #       contents_encryption_mode: 0x1
409                 #       filenames_encryption_mode: 0x4
410                 #       flags: 0x2
411                 #       master_key_descriptor: 0000000000000000
412                 #       nonce: EFBD18765DF6414EC0A2CD5F91297E12
413                 #
414                 # Also support the case where the whole xattr is printed as hex,
415                 # as is the case for fscrypt_context_v2.
416                 #
417                 #       xattr: e_name_index:9 e_name:c e_name_len:1 e_value_size:40 e_value:
418                 #       020104020000000033809BFEBE68A4AD264079B30861DD5E6B9E72D07523C58794ACF52534BAA756
419                 #
420                 $DUMP_F2FS_PROG -i $inode $device | awk '
421                         /\<e_name:c\>/ { found = 1 }
422                         (/^nonce:/ || /^[[:xdigit:]]+$/) && found {
423                                 print substr($0, length($0) - 31, 32);
424                                 found = 0;
425                         }'
426                 ;;
427         *)
428                 _fail "_get_encryption_nonce() isn't implemented on $FSTYP"
429                 ;;
430         esac
431 }
432
433 # Require support for _get_encryption_nonce()
434 _require_get_encryption_nonce_support()
435 {
436         echo "Checking for _get_encryption_nonce() support for $FSTYP" >> $seqres.full
437         case $FSTYP in
438         ext4)
439                 _require_command "$DEBUGFS_PROG" debugfs
440                 ;;
441         f2fs)
442                 _require_command "$DUMP_F2FS_PROG" dump.f2fs
443                 # For fscrypt_context_v2, we actually need a f2fs-tools version
444                 # that has the patch "f2fs-tools: improve xattr value printing"
445                 # (https://sourceforge.net/p/linux-f2fs/mailman/message/36648640/).
446                 # Otherwise the xattr is incorrectly parsed as v1.  But just let
447                 # the test fail in that case, as it was an f2fs-tools bug...
448                 ;;
449         *)
450                 _notrun "_get_encryption_nonce() isn't implemented on $FSTYP"
451                 ;;
452         esac
453 }
454
455 # Retrieve the encrypted filename stored on-disk for the given file.
456 # The name is printed to stdout in binary.
457 _get_ciphertext_filename()
458 {
459         local device=$1
460         local inode=$2
461         local dir_inode=$3
462
463         case $FSTYP in
464         ext4)
465                 # Extract the filename from the debugfs output line like:
466                 #
467                 #  131075  100644 (1)      0      0       0 22-Apr-2019 16:54 \xa2\x85\xb0z\x13\xe9\x09\x86R\xed\xdc\xce\xad\x14d\x19
468                 #
469                 # Bytes are shown either literally or as \xHH-style escape
470                 # sequences; we have to decode the escaped bytes here.
471                 #
472                 $DEBUGFS_PROG $device -R "ls -l -r <$dir_inode>" \
473                                         2>>$seqres.full | perl -ne '
474                         next if not /^\s*'$inode'\s+/;
475                         s/.*?\d\d:\d\d //;
476                         chomp;
477                         s/\\x([[:xdigit:]]{2})/chr hex $1/eg;
478                         print;'
479                 ;;
480         f2fs)
481                 # Extract the filename from the dump.f2fs output line like:
482                 #
483                 #  i_name                                       [UpkzIPuts9by1oDmE+Ivfw]
484                 #
485                 # The name is shown base64-encoded; we have to decode it here.
486                 #
487                 $DUMP_F2FS_PROG $device -i $inode | perl -ne '
488                         next if not /^i_name\s+\[([A-Za-z0-9+,]+)\]/;
489                         chomp $1;
490                         my @chars = split //, $1;
491                         my $ac = 0;
492                         my $bits = 0;
493                         my $table = join "", (A..Z, a..z, 0..9, "+", ",");
494                         foreach (@chars) {
495                                 $ac += index($table, $_) << $bits;
496                                 $bits += 6;
497                                 if ($bits >= 8) {
498                                         print chr($ac & 0xff);
499                                         $ac >>= 8;
500                                         $bits -= 8;
501                                 }
502                         }
503                         if ($ac != 0) {
504                                 print STDERR "Invalid base64-encoded string!\n";
505                         }'
506                 ;;
507         *)
508                 _fail "_get_ciphertext_filename() isn't implemented on $FSTYP"
509                 ;;
510         esac
511 }
512
513 # Require support for _get_ciphertext_filename().
514 _require_get_ciphertext_filename_support()
515 {
516         echo "Checking for _get_ciphertext_filename() support for $FSTYP" >> $seqres.full
517         case $FSTYP in
518         ext4)
519                 # Verify that the "ls -l -r" debugfs command is supported and
520                 # that it hex-encodes non-ASCII characters, rather than using an
521                 # ambiguous escaping method.  This requires e2fsprogs v1.45.1 or
522                 # later; or more specifically, a version that has the commit
523                 # "debugfs: avoid ambiguity when printing filenames".
524                 _require_command "$DEBUGFS_PROG" debugfs
525                 _scratch_mount
526                 touch $SCRATCH_MNT/$'\xc1'
527                 _scratch_unmount
528                 if ! $DEBUGFS_PROG $SCRATCH_DEV -R "ls -l -r /" 2>&1 \
529                         | tee -a $seqres.full | grep -E -q '\s+\\xc1\s*$'; then
530                         _notrun "debugfs (e2fsprogs) is too old; doesn't support showing unambiguous on-disk filenames"
531                 fi
532                 ;;
533         f2fs)
534                 # Verify that dump.f2fs shows encrypted filenames in full.  This
535                 # requires f2fs-tools v1.13.0 or later; or more specifically, a
536                 # version that has the commit
537                 # "f2fs-tools: improve filename printing".
538
539                 _require_command "$DUMP_F2FS_PROG" dump.f2fs
540                 _require_command "$KEYCTL_PROG" keyctl
541                 _scratch_mount
542                 _new_session_keyring
543
544                 local keydesc=$(_generate_session_encryption_key)
545                 local dir=$SCRATCH_MNT/test.${FUNCNAME[0]}
546                 local file=$dir/$(perl -e 'print "A" x 255')
547                 mkdir $dir
548                 _set_encpolicy $dir $keydesc
549                 touch $file
550                 local inode=$(stat -c %i $file)
551
552                 _scratch_unmount
553                 $KEYCTL_PROG clear @s
554
555                 # 255-character filename should result in 340 base64 characters.
556                 if ! $DUMP_F2FS_PROG -i $inode $SCRATCH_DEV \
557                         | grep -E -q '^i_name[[:space:]]+\[[A-Za-z0-9+,]{340}\]'; then
558                         _notrun "dump.f2fs (f2fs-tools) is too old; doesn't support showing unambiguous on-disk filenames"
559                 fi
560                 ;;
561         *)
562                 _notrun "_get_ciphertext_filename() isn't implemented on $FSTYP"
563                 ;;
564         esac
565 }
566
567 # Get an encrypted file's list of on-disk blocks as a comma-separated list of
568 # block offsets from the start of the device.  "Blocks" are 512 bytes each here.
569 _get_ciphertext_block_list()
570 {
571         local file=$1
572
573         sync
574         $XFS_IO_PROG -c fiemap $file | perl -ne '
575                 next if not /^\s*\d+: \[\d+\.\.\d+\]: (\d+)\.\.(\d+)/;
576                 print $_ . "," foreach $1..$2;' | sed 's/,$//'
577 }
578
579 # Dump a block list that was previously saved by _get_ciphertext_block_list().
580 _dump_ciphertext_blocks()
581 {
582         local device=$1
583         local blocklist=$2
584         local block
585
586         for block in $(tr ',' ' ' <<< $blocklist); do
587                 dd if=$device bs=512 count=1 skip=$block status=none
588         done
589 }
590
591 _do_verify_ciphertext_for_encryption_policy()
592 {
593         local contents_encryption_mode=$1
594         local filenames_encryption_mode=$2
595         local policy_flags=$3
596         local set_encpolicy_args=$4
597         local keyspec=$5
598         local raw_key_hex=$6
599         local crypt_contents_cmd="$here/src/fscrypt-crypt-util $7"
600         local crypt_filename_cmd="$here/src/fscrypt-crypt-util $8"
601
602         local blocksize=$(_get_block_size $SCRATCH_MNT)
603         local test_contents_files=()
604         local test_filenames_files=()
605         local i src dir dst inode blocklist \
606               padding_flag padding dir_inode len name f nonce decrypted_name
607
608         # Create files whose encrypted contents we'll verify.  For each, save
609         # the information: (copy of original file, inode number of encrypted
610         # file, comma-separated block list) into test_contents_files[].
611         echo "Creating files for contents verification" >> $seqres.full
612         i=1
613         rm -f $tmp.testfile_*
614         for src in /dev/zero /dev/urandom; do
615                 head -c $((4 * blocksize)) $src > $tmp.testfile_$i
616                 (( i++ ))
617         done
618         dir=$SCRATCH_MNT/encdir
619         mkdir $dir
620         _set_encpolicy $dir $keyspec $set_encpolicy_args -f $policy_flags
621         for src in $tmp.testfile_*; do
622                 dst=$dir/${src##*.}
623                 cp $src $dst
624                 inode=$(stat -c %i $dst)
625                 blocklist=$(_get_ciphertext_block_list $dst)
626                 test_contents_files+=("$src $inode $blocklist")
627         done
628
629         # Create files whose encrypted names we'll verify.  For each, save the
630         # information: (original filename, inode number of encrypted file, inode
631         # of parent directory, padding amount) into test_filenames_files[].  Try
632         # each padding amount: 4, 8, 16, or 32 bytes.  Also try various filename
633         # lengths, including boundary cases.  Assume NAME_MAX == 255.
634         echo "Creating files for filenames verification" >> $seqres.full
635         for padding_flag in 0 1 2 3; do
636                 padding=$((4 << padding_flag))
637                 dir=$SCRATCH_MNT/encdir.pad$padding
638                 mkdir $dir
639                 dir_inode=$(stat -c %i $dir)
640                 _set_encpolicy $dir $keyspec $set_encpolicy_args \
641                         -f $((policy_flags | padding_flag))
642                 for len in 1 3 15 16 17 32 100 254 255; do
643                         name=$(tr -d -C a-zA-Z0-9 < /dev/urandom | head -c $len)
644                         touch $dir/$name
645                         inode=$(stat -c %i $dir/$name)
646                         test_filenames_files+=("$name $inode $dir_inode $padding")
647                 done
648         done
649
650         # Now unmount the filesystem and verify the ciphertext we just wrote.
651         _scratch_unmount
652
653         echo "Verifying encrypted file contents" >> $seqres.full
654         for f in "${test_contents_files[@]}"; do
655                 read -r src inode blocklist <<< "$f"
656                 nonce=$(_get_encryption_nonce $SCRATCH_DEV $inode)
657                 _dump_ciphertext_blocks $SCRATCH_DEV $blocklist > $tmp.actual_contents
658                 $crypt_contents_cmd $contents_encryption_mode $raw_key_hex \
659                         --file-nonce=$nonce --block-size=$blocksize \
660                         --inode-number=$inode < $src > $tmp.expected_contents
661                 if ! cmp $tmp.expected_contents $tmp.actual_contents; then
662                         _fail "Expected encrypted contents != actual encrypted contents.  File: $f"
663                 fi
664                 $crypt_contents_cmd $contents_encryption_mode $raw_key_hex \
665                         --decrypt --file-nonce=$nonce --block-size=$blocksize \
666                         --inode-number=$inode \
667                         < $tmp.actual_contents > $tmp.decrypted_contents
668                 if ! cmp $src $tmp.decrypted_contents; then
669                         _fail "Contents decryption sanity check failed.  File: $f"
670                 fi
671         done
672
673         echo "Verifying encrypted file names" >> $seqres.full
674         for f in "${test_filenames_files[@]}"; do
675                 read -r name inode dir_inode padding <<< "$f"
676                 nonce=$(_get_encryption_nonce $SCRATCH_DEV $dir_inode)
677                 _get_ciphertext_filename $SCRATCH_DEV $inode $dir_inode \
678                         > $tmp.actual_name
679                 echo -n "$name" | \
680                         $crypt_filename_cmd $filenames_encryption_mode \
681                         $raw_key_hex --file-nonce=$nonce --padding=$padding \
682                         --block-size=255 --inode-number=$dir_inode \
683                         > $tmp.expected_name
684                 if ! cmp $tmp.expected_name $tmp.actual_name; then
685                         _fail "Expected encrypted filename != actual encrypted filename.  File: $f"
686                 fi
687                 $crypt_filename_cmd $filenames_encryption_mode $raw_key_hex \
688                         --decrypt --file-nonce=$nonce --padding=$padding \
689                         --block-size=255 --inode-number=$dir_inode \
690                         < $tmp.actual_name > $tmp.decrypted_name
691                 decrypted_name=$(tr -d '\0' < $tmp.decrypted_name)
692                 if [ "$name" != "$decrypted_name" ]; then
693                         _fail "Filename decryption sanity check failed ($name != $decrypted_name).  File: $f"
694                 fi
695         done
696 }
697
698 # fscrypt UAPI constants (see <linux/fscrypt.h>)
699
700 FSCRYPT_MODE_AES_256_XTS=1
701 FSCRYPT_MODE_AES_256_CTS=4
702 FSCRYPT_MODE_AES_128_CBC=5
703 FSCRYPT_MODE_AES_128_CTS=6
704 FSCRYPT_MODE_ADIANTUM=9
705
706 FSCRYPT_POLICY_FLAG_DIRECT_KEY=0x04
707 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64=0x08
708
709 _fscrypt_mode_name_to_num()
710 {
711         local name=$1
712
713         case "$name" in
714         AES-256-XTS)            echo $FSCRYPT_MODE_AES_256_XTS ;;
715         AES-256-CTS-CBC)        echo $FSCRYPT_MODE_AES_256_CTS ;;
716         AES-128-CBC-ESSIV)      echo $FSCRYPT_MODE_AES_128_CBC ;;
717         AES-128-CTS-CBC)        echo $FSCRYPT_MODE_AES_128_CTS ;;
718         Adiantum)               echo $FSCRYPT_MODE_ADIANTUM ;;
719         *)                      _fail "Unknown fscrypt mode: $name" ;;
720         esac
721 }
722
723 # Verify that file contents and names are encrypted correctly when an encryption
724 # policy of the specified type is used.
725 #
726 # The first two parameters are the contents and filenames encryption modes to
727 # test.  The following optional parameters are also accepted to further modify
728 # the type of encryption policy that is tested:
729 #
730 #       'v2':                   test a v2 encryption policy
731 #       'direct':               test the DIRECT_KEY policy flag
732 #       'iv_ino_lblk_64':       test the IV_INO_LBLK_64 policy flag
733 #
734 _verify_ciphertext_for_encryption_policy()
735 {
736         local contents_encryption_mode=$1
737         local filenames_encryption_mode=$2
738         local opt
739         local policy_version=1
740         local policy_flags=0
741         local set_encpolicy_args=""
742         local crypt_util_args=""
743         local crypt_util_contents_args=""
744         local crypt_util_filename_args=""
745
746         shift 2
747         for opt; do
748                 case "$opt" in
749                 v2)
750                         policy_version=2
751                         ;;
752                 direct)
753                         if [ $contents_encryption_mode != \
754                              $filenames_encryption_mode ]; then
755                                 _fail "For direct key mode, contents and filenames modes must match"
756                         fi
757                         (( policy_flags |= FSCRYPT_POLICY_FLAG_DIRECT_KEY ))
758                         ;;
759                 iv_ino_lblk_64)
760                         (( policy_flags |= FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 ))
761                         ;;
762                 *)
763                         _fail "Unknown option '$opt' passed to ${FUNCNAME[0]}"
764                         ;;
765                 esac
766         done
767         local contents_mode_num=$(_fscrypt_mode_name_to_num $contents_encryption_mode)
768         local filenames_mode_num=$(_fscrypt_mode_name_to_num $filenames_encryption_mode)
769
770         set_encpolicy_args+=" -c $contents_mode_num"
771         set_encpolicy_args+=" -n $filenames_mode_num"
772
773         if (( policy_version > 1 )); then
774                 set_encpolicy_args+=" -v 2"
775                 crypt_util_args+=" --kdf=HKDF-SHA512"
776                 if (( policy_flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY )); then
777                         if (( policy_flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 )); then
778                                 _fail "'direct' and 'iv_ino_lblk_64' options are mutually exclusive"
779                         fi
780                         crypt_util_args+=" --mode-num=$contents_mode_num"
781                 elif (( policy_flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 )); then
782                         crypt_util_args+=" --iv-ino-lblk-64"
783                         crypt_util_contents_args+=" --mode-num=$contents_mode_num"
784                         crypt_util_filename_args+=" --mode-num=$filenames_mode_num"
785                 fi
786         else
787                 if (( policy_flags & ~FSCRYPT_POLICY_FLAG_DIRECT_KEY )); then
788                         _fail "unsupported flags for v1 policy: $policy_flags"
789                 fi
790                 if (( policy_flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY )); then
791                         crypt_util_args+=" --kdf=none"
792                 else
793                         crypt_util_args+=" --kdf=AES-128-ECB"
794                 fi
795         fi
796         set_encpolicy_args=${set_encpolicy_args# }
797
798         _require_scratch_encryption $set_encpolicy_args -f $policy_flags
799         _require_test_program "fscrypt-crypt-util"
800         _require_xfs_io_command "fiemap"
801         _require_get_encryption_nonce_support
802         _require_get_ciphertext_filename_support
803         if (( policy_version == 1 )); then
804                 _require_command "$KEYCTL_PROG" keyctl
805         fi
806
807         echo "Creating encryption-capable filesystem" >> $seqres.full
808         if (( policy_flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 )); then
809                 _scratch_mkfs_stable_inodes_encrypted &>> $seqres.full
810         else
811                 _scratch_mkfs_encrypted &>> $seqres.full
812         fi
813         _scratch_mount
814
815         crypt_util_args+=" --fs-uuid=$(blkid -s UUID -o value $SCRATCH_DEV | tr -d -)"
816
817         crypt_util_contents_args+="$crypt_util_args"
818         crypt_util_filename_args+="$crypt_util_args"
819
820         echo "Generating encryption key" >> $seqres.full
821         local raw_key=$(_generate_raw_encryption_key)
822         if (( policy_version > 1 )); then
823                 local keyspec=$(_add_enckey $SCRATCH_MNT "$raw_key" \
824                                 | awk '{print $NF}')
825         else
826                 local keyspec=$(_generate_key_descriptor)
827                 _new_session_keyring
828                 _add_session_encryption_key $keyspec $raw_key
829         fi
830         local raw_key_hex=$(echo "$raw_key" | tr -d '\\x')
831
832         echo
833         echo -e "Verifying ciphertext with parameters:"
834         echo -e "\tcontents_encryption_mode: $contents_encryption_mode"
835         echo -e "\tfilenames_encryption_mode: $filenames_encryption_mode"
836         [ $# -ne 0 ] && echo -e "\toptions: $*"
837
838         _do_verify_ciphertext_for_encryption_policy \
839                 "$contents_encryption_mode" \
840                 "$filenames_encryption_mode" \
841                 "$policy_flags" \
842                 "$set_encpolicy_args" \
843                 "$keyspec" \
844                 "$raw_key_hex" \
845                 "$crypt_util_contents_args" \
846                 "$crypt_util_filename_args"
847 }