#!/bin/bash
#
# Test cryptsetup/authenticated encryption compatibility.
#
[ -z "$CRYPTSETUP_PATH" ] && CRYPTSETUP_PATH=".."
CRYPTSETUP=$CRYPTSETUP_PATH/cryptsetup
DEV_NAME=dmi_test
DEV_NAME2=dmi_test_xdif
DEV=mode-test.img
HEADER_IMG=mode-test-detached.img
PWD1=nHjJHjI23JK
KEY_FILE=key.img
FAST_PBKDF_OPT="--pbkdf pbkdf2 --pbkdf-force-iterations 1000"

if [ -n "$CRYPTSETUP_TESTS_RUN_IN_MESON" ]; then
	CRYPTSETUP_VALGRIND=$CRYPTSETUP
else
	CRYPTSETUP_VALGRIND=../.libs/cryptsetup
	CRYPTSETUP_LIB_VALGRIND=../.libs
fi

dmremove() { # device
	udevadm settle >/dev/null 2>&1
	dmsetup remove --retry $1 >/dev/null 2>&1
}

cleanup() {
	[ -b /dev/mapper/$DEV_NAME ] && dmremove $DEV_NAME
	[ -b /dev/mapper/$DEV_NAME2 ] && dmremove $DEV_NAME2
	[ -b /dev/mapper/"$DEV_NAME"_dif ] && dmremove "$DEV_NAME"_dif
	[ -n "$DEV_LOOP" ] && losetup -d "$DEV_LOOP"
	DEV_LOOP=""
	rm -f $DEV $KEY_FILE $HEADER_IMG >/dev/null 2>&1
}

fail()
{
	echo
	[ -n "$1" ] && echo "FAIL: $1"
	echo "FAILED backtrace:"
	while caller $frame; do ((frame++)); done
	cleanup
	exit 100
}

_sigchld() { local c=$?; [ $c -eq 139 ] && fail "Segfault"; [ $c -eq 134 ] && fail "Aborted"; }
trap _sigchld CHLD

skip()
{
	[ -n "$1" ] && echo "$1"
	exit 77
}

valgrind_setup()
{
	command -v valgrind >/dev/null || fail "Cannot find valgrind."
	[ ! -f $CRYPTSETUP_VALGRIND ] && fail "Unable to get location of cryptsetup executable."
	[ ! -f valg.sh ] && fail "Unable to get location of valg runner script."
	if [ -z "$CRYPTSETUP_TESTS_RUN_IN_MESON" ]; then
		export LD_LIBRARY_PATH="$CRYPTSETUP_LIB_VALGRIND:$LD_LIBRARY_PATH"
	fi
}

valgrind_run()
{
	INFOSTRING="$(basename ${BASH_SOURCE[1]})-line-${BASH_LINENO[0]}" ./valg.sh ${CRYPTSETUP_VALGRIND} "$@"
}

dm_integrity_inline_support()
{
	VER_STR=$(dmsetup targets | grep integrity | cut -f2 -dv)
	[ -z "$VER_STR" ] && fail "Failed to parse dm-integrity version."

	VER_MAJ=$(echo $VER_STR | cut -f 1 -d.)
	VER_MIN=$(echo $VER_STR | cut -f 2 -d.)

	[ $VER_MAJ -gt 1 ] && return 0
	if [ $VER_MIN -ge 12 ]; then
		return 0
	fi
	return 1
}

add_device() {
	cleanup
	dd if=/dev/urandom of=$KEY_FILE bs=1 count=512 >/dev/null 2>&1
	dd if=/dev/zero of=$DEV bs=1M count=32 >/dev/null 2>&1
	IDEV=$DEV
	INLINE_PARAMS=""
}

add_device_inline() {
	add_device
	DEV_LOOP=$(losetup -f $DEV --show)
	[ -z "$DEV_LOOP" ] && fail
	dmsetup create $DEV_NAME2 --table "0 32768 integrity $DEV_LOOP 0 64 J 2 block_size:4096 fix_padding"
	[ ! -b /dev/mapper/$DEV_NAME2 ] && fail
	IDEV=/dev/mapper/$DEV_NAME2
	INLINE_PARAMS="--integrity-inline "
}

set_LO_DEV() { # file
	# support both /dev/loopX and /dev/loop/X
	LO_DEV=$(losetup -l -O NAME -n -j $1 2>/dev/null | sed -e 's/loop\//loop/')
}

status_check() # name value [detached]
{
	if [ -n "$3" ]; then
		PARAMS="$DEV_NAME --header $HEADER_IMG"
	else
		PARAMS="$DEV_NAME"
	fi

#	$CRYPTSETUP status $PARAMS

	X=$($CRYPTSETUP status $PARAMS | grep -m1 "$1" | sed -e 's/.*:[ \t]\+//' | cut -d' ' -f1)
	if [ "$X" != "$2" ] ; then
		echo "[status FAIL]"
		echo " Expecting $1:$2 got \"$X\"."
		fail
	fi
}

dump_check() # name value
{
	X=$($CRYPTSETUP luksDump $IDEV | grep -m1 "$1" | sed -e 's/.*:[ \t]\+//' | cut -d' ' -f1)
	if [ "$X" != "$2" ] ; then
		echo "[dump FAIL]"
		echo " Expecting $1:$2 got \"$X\"."
		fail
	fi
}

int_check_sum() # alg checksum
{
	VSUM=$(sha256sum /dev/mapper/$DEV_NAME | cut -d' ' -f 1)
	if [ "$VSUM" = "$2" ] ; then
		echo -n "[CHECKSUM]"
	else
		echo "[FAIL]"
		echo " Expecting $2 got $VSUM."
		fail
	fi
}

int_error_detection() # alg int sector_size
{
	echo -n "[DETECT_CORRUPTION]"
	echo -n "XXXXX" | dd of=$IDEV bs=1M seek=8 count=1 conv=notrunc >/dev/null 2>&1 || fail "Cannot write to device."
	$CRYPTSETUP open -d $KEY_FILE $IDEV $DEV_NAME || fail "Cannot activate device."
	dd if=/dev/mapper/$DEV_NAME  of=/dev/null >/dev/null 2>&1 && fail "Error detection failed."
	$CRYPTSETUP close $DEV_NAME || fail "Cannot deactivate device."
}

intformat() # alg integrity integrity_out key_size int_key_size sector_size csum [test_hdr]
{
	echo -n "[$1:$2:$4:$6:$5]"
	echo -n "[FORMAT]"

	# just trick, if int key size is not multiple of 16, use explicit flag
	if [ $(($5 % 16)) -eq 0 ]; then
		INT_PARAMS="--integrity $2 --integrity-legacy-padding"
	else
		INT_PARAMS="--integrity $2 --integrity-key-size $5 --integrity-legacy-padding"
	fi

	$CRYPTSETUP luksFormat --type luks2 -q -c $1 $INT_PARAMS $INLINE_PARAMS --sector-size $6 -s $4 \
		$FAST_PBKDF_OPT -d $KEY_FILE $IDEV --offset 8192 >/dev/null 2>&1
	if [ $? -ne 0 ] ; then
		echo "[N/A]"
		return
	fi
	dump_check "cipher" $1
	dump_check "sector" $6
	dump_check "integrity" $3
	dump_check "Key:" $(($4 + $5))
	echo -n "[ACTIVATE]"
	$CRYPTSETUP open -d $KEY_FILE $IDEV $DEV_NAME || fail "Cannot activate device."
	set_LO_DEV $IDEV
	status_check "cipher" $1
	status_check "sector size" $6
	status_check "integrity:" $3
	status_check "keysize:" $(($4 + $5))
	[ -n "$LO_DEV" ] && status_check "device:" $LO_DEV
	[ $5 -gt 0 ] && status_check "integrity keysize:" $5
	int_check_sum $1 $7
	echo -n "[SUSPEND]"
	$CRYPTSETUP luksSuspend $DEV_NAME || fail "Cannot suspend device."
	dmsetup info $DEV_NAME | grep -q SUSPENDED || fail "Not suspended."
	if [ -z "$INLINE_PARAMS" ]; then
		dmsetup info "$DEV_NAME"_dif | grep -q SUSPENDED || fail "Not suspended."
	else
		# this hw-inline device must not be suspended
		dmsetup info "$DEV_NAME2" | grep -q ACTIVE || fail
	fi
	echo -n "[RESUME]"
	$CRYPTSETUP luksResume -d $KEY_FILE $DEV_NAME || fail "Cannot resume device."
	dmsetup info $DEV_NAME | grep -q ACTIVE || fail "Not resumed."
	if [ -z "$INLINE_PARAMS" ]; then
		dmsetup info "$DEV_NAME"_dif | grep -q ACTIVE || fail "Not resumed."
	fi
	echo -n "[REMOVE]"
	$CRYPTSETUP close $DEV_NAME || fail "Cannot deactivate device."
	[ -b /dev/mapper/"$DEV_NAME"_dif ] && fail
	# check detached header activation
	if [ -n "$8" ] ; then
		echo -n "[DETACHED_HDR]"
		$CRYPTSETUP luksHeaderBackup -q --header-backup-file $HEADER_IMG $IDEV || fail
		wipefs -a $IDEV >/dev/null 2>&1  || fail
		$CRYPTSETUP open --header $HEADER_IMG -d $KEY_FILE $IDEV $DEV_NAME || fail "Cannot activate device."
		set_LO_DEV $IDEV
		status_check "cipher" $1 1
		status_check "sector size" $6 1
		status_check "integrity:" $3 1
		status_check "keysize:" $(($4 + $5)) 1
		[ -n "$LO_DEV" ] && status_check "device:" $LO_DEV 1
		[ $5 -gt 0 ] && status_check "integrity keysize:" $5 1
		int_check_sum $1 $7
		# check status returns values even if no --header is set
		status_check "cipher" $1
		status_check "sector size" $6
		status_check "integrity:" $3
		status_check "keysize:" $(($4 + $5))
		[ -n "$LO_DEV" ] && status_check "device:" $LO_DEV
		[ $5 -gt 0 ] && status_check "integrity keysize:" $5
		$CRYPTSETUP close $DEV_NAME || fail "Cannot deactivate device."
		[ -b /dev/mapper/"$DEV_NAME"_dif ] && fail
		$CRYPTSETUP luksHeaderRestore -q --header-backup-file $HEADER_IMG $IDEV || fail
		rm -f $HEADER_IMG
	fi

	int_error_detection
	echo "[OK]"
}

[ $(id -u) != 0 ] && skip "WARNING: You must be root to run this test, test skipped."
[ ! -x "$CRYPTSETUP" ] && skip "Cannot find $CRYPTSETUP, test skipped."
[ -n "$VALG" ] && valgrind_setup && CRYPTSETUP=valgrind_run
modprobe dm-integrity >/dev/null 2>&1
dmsetup targets | grep integrity >/dev/null 2>&1 || skip "Cannot find dm-integrity target, test skipped."
command -v wipefs >/dev/null ||  skip "Cannot find wipefs, test skipped."

echo "LUKS2 authenticated mode test"
add_device

intformat aes-cbc-essiv:sha256 hmac-sha256 hmac\(sha256\) 128 256  512 ee501705a084cd0ab6f4a28014bcf62b8bfa3434de00b82743c50b3abf06232c 1
intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 256 256  512 ee501705a084cd0ab6f4a28014bcf62b8bfa3434de00b82743c50b3abf06232c 1
intformat aes-xts-random       hmac-sha256 hmac\(sha256\) 256 256  512 492c2d1cc9e222a850c399bfef4ed5a86bf5afc59e54f0f0c7ba8e2a64548323
intformat aes-cbc-essiv:sha256 hmac-sha256 hmac\(sha256\) 256 256  512 ee501705a084cd0ab6f4a28014bcf62b8bfa3434de00b82743c50b3abf06232c
intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 512 256  512 ee501705a084cd0ab6f4a28014bcf62b8bfa3434de00b82743c50b3abf06232c
intformat aes-xts-random       hmac-sha256 hmac\(sha256\) 512 256  512 492c2d1cc9e222a850c399bfef4ed5a86bf5afc59e54f0f0c7ba8e2a64548323
intformat aes-cbc-essiv:sha256 hmac-sha256 hmac\(sha256\) 128 256 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b
intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 256 256 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b
intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 256 256 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b 1
intformat aes-xts-random       hmac-sha256 hmac\(sha256\) 256 256 4096 8c0463f5ac09613674bdf40b0ff6f985edbc3de04e51fdc688873cb333ef3cda
intformat aes-cbc-essiv:sha256 hmac-sha256 hmac\(sha256\) 256 256 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b
intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 512 256 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b
intformat aes-xts-random       hmac-sha256 hmac\(sha256\) 512 256 4096 8c0463f5ac09613674bdf40b0ff6f985edbc3de04e51fdc688873cb333ef3cda

intformat aes-cbc-essiv:sha256 hmac-sha512 hmac\(sha512\) 256 512 4096 9873d864fccb866521e79c9f0f75ad0c578d6bd7620399bbf4779e698c6e92fd
intformat aes-xts-essiv:sha256 hmac-sha512 hmac\(sha512\) 512 512 4096 9873d864fccb866521e79c9f0f75ad0c578d6bd7620399bbf4779e698c6e92fd
intformat aes-xts-plain64      hmac-sha512 hmac\(sha512\) 512 512 4096 9873d864fccb866521e79c9f0f75ad0c578d6bd7620399bbf4779e698c6e92fd
intformat aes-xts-random       hmac-sha512 hmac\(sha512\) 512 512 4096 621f6c03f7361c2bf8f10059ae822339223f8471c750b0cf8584fba7134bd4a2

intformat aes-xts-plain64 hmac-sha1 hmac\(sha1\) 512 160 4096 7370c66a92708fb71b186931468be6aa9b26f4f88373b00b1c57360b9ee1304e
intformat aes-xts-random  hmac-sha1 hmac\(sha1\) 512 160 4096 8c0463f5ac09613674bdf40b0ff6f985edbc3de04e51fdc688873cb333ef3cda

intformat aes-xts-plain64 hmac-sha256 hmac\(sha256\) 512 264 512 ee501705a084cd0ab6f4a28014bcf62b8bfa3434de00b82743c50b3abf06232c
intformat aes-xts-plain64 hmac-sha512 hmac\(sha512\) 512 792 512 9040d276d8bfab30bbc4bf389e152e08c13ac6fa84d49d11c1bee6e1638fd8f1

intformat aes-gcm-random aead aead 128 0  512 5f6f3f6be03c74d9aaaeaf40dd310c99a20e2786045f78a1fc6a0b189d231f57
intformat aes-gcm-random aead aead 128 0 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b
intformat aes-gcm-random aead aead 256 0  512 5f6f3f6be03c74d9aaaeaf40dd310c99a20e2786045f78a1fc6a0b189d231f57
intformat aes-gcm-random aead aead 256 0 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b

intformat aes-ccm-random aead aead 152 0  512 288e5e9bc5be6c0bd2a74abbb72c7944da83198b5e3041dcf159e7ae250dafa8
intformat aes-ccm-random aead aead 152 0 4096 7370c66a92708fb71b186931468be6aa9b26f4f88373b00b1c57360b9ee1304e
intformat aes-ccm-random aead aead 280 0  512 288e5e9bc5be6c0bd2a74abbb72c7944da83198b5e3041dcf159e7ae250dafa8
intformat aes-ccm-random aead aead 280 0 4096 7370c66a92708fb71b186931468be6aa9b26f4f88373b00b1c57360b9ee1304e

intformat chacha20-plain64 poly1305 poly1305 256 0  512 3f82eae753ff52a689ddc559c691bbdff838361bbe9a3ce8c7212e16e51b5dbe
intformat chacha20-random  poly1305 poly1305 256 0  512 5f6f3f6be03c74d9aaaeaf40dd310c99a20e2786045f78a1fc6a0b189d231f57
intformat chacha20-plain64 poly1305 poly1305 256 0 4096 7370c66a92708fb71b186931468be6aa9b26f4f88373b00b1c57360b9ee1304e
intformat chacha20-random  poly1305 poly1305 256 0 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b

intformat aegis128-random  aead aead 128 0  512 ee501705a084cd0ab6f4a28014bcf62b8bfa3434de00b82743c50b3abf06232c 1
intformat aegis128-random  aead aead 128 0 4096 358d6beceddf593aff6b22c31684e0df9c226330aff5812e060950215217d21b 1

if dm_integrity_inline_support; then
	echo "LUKS2 authenticated mode test (inline tags)"
	add_device_inline

	intformat aes-cbc-essiv:sha256 hmac-sha256 hmac\(sha256\) 128 256 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723
	intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 256 256 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723
	intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 256 256 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723 1
	intformat aes-xts-random       hmac-sha256 hmac\(sha256\) 256 256 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723
	intformat aes-cbc-essiv:sha256 hmac-sha256 hmac\(sha256\) 256 256 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723
	intformat aes-xts-plain64      hmac-sha256 hmac\(sha256\) 512 256 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723

	intformat aes-gcm-random aead aead 128 0 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723

	intformat chacha20-plain64 poly1305 poly1305 256 0 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723
	intformat chacha20-random  poly1305 poly1305 256 0 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723

	intformat aegis128-random  aead aead 128 0 4096 cfadd44a103cbd6d5726fa07b27d7aad2f67ed3930ff96901c486a5beaf7e723 1
fi

cleanup
