From 1f01eea60e38ac92aa05e4b95372d54b7b9095df Mon Sep 17 00:00:00 2001
From: Milan Broz <gmazyland@gmail.com>
Date: Mon, 26 Jun 2023 13:25:59 +0200
Subject: [PATCH 1/2] Fix reencryption to fail properly for unknown cipher.

crypt_get_cipher and crypt_get_cipher mode can return NULL,
check it in advance.
---
 src/utils_reencrypt.c | 6 ++++++
 1 file changed, 6 insertions(+)

Index: cryptsetup-2.3.7/src/cryptsetup.c
===================================================================
--- cryptsetup-2.3.7.orig/src/cryptsetup.c
+++ cryptsetup-2.3.7/src/cryptsetup.c
@@ -2999,6 +2999,12 @@ static int action_encrypt_luks2(struct c
 	if (r < 0)
 		goto err;
 
+	if (!crypt_get_cipher(*cd)) {
+		log_err(_("No known cipher specification pattern detected in LUKS2 header."));
+		r = -EINVAL;
+		goto err;
+	}
+
 	if (opt_data_shift) {
 		params.data_shift = imaxabs(opt_data_shift) / SECTOR_SIZE,
 		params.resilience = "datashift";
@@ -3068,6 +3074,11 @@ static int action_decrypt_luks2(struct c
 	};
 	size_t passwordLen;
 
+	if (!crypt_get_cipher(cd)) {
+		log_err(_("No known cipher specification pattern detected in LUKS2 header."));
+		return -EINVAL;
+	}
+
 	if (!crypt_get_metadata_device_name(cd) || !crypt_get_device_name(cd) ||
 	    !strcmp(crypt_get_metadata_device_name(cd), crypt_get_device_name(cd))) {
 		log_err(_("LUKS2 decryption is supported with detached header device only."));
@@ -3289,6 +3300,11 @@ static int action_reencrypt_luks2(struct
 		.luks2 = &luks2_params,
 	};
 
+	if (!crypt_get_cipher(cd)) {
+		log_err(_("No known cipher specification pattern detected in LUKS2 header."));
+		return -EINVAL;
+	}
+
 	_set_reencryption_flags(&params.flags);
 
 	if (!opt_cipher && crypt_is_cipher_null(crypt_get_cipher(cd))) {
Index: cryptsetup-2.3.7/src/cryptsetup_reencrypt.c
===================================================================
--- cryptsetup-2.3.7.orig/src/cryptsetup_reencrypt.c
+++ cryptsetup-2.3.7/src/cryptsetup_reencrypt.c
@@ -185,6 +185,11 @@ static int set_reencrypt_requirement(con
 	    crypt_persistent_flags_get(cd, CRYPT_FLAGS_REQUIREMENTS, &reqs))
 		goto out;
 
+	if (!crypt_get_cipher(cd)) {
+		log_err(_("No known cipher specification pattern detected in LUKS2 header."));
+		goto out;
+	}
+
 	/* reencrypt already in-progress */
 	if (reqs & CRYPT_REQUIREMENT_OFFLINE_REENCRYPT) {
 		log_err(_("Reencryption already in-progress."));
@@ -709,6 +714,12 @@ static int backup_luks_headers(struct re
 	    (r = crypt_load(cd, CRYPT_LUKS, NULL)))
 		goto out;
 
+	if (!crypt_get_cipher(cd)) {
+		log_err(_("No known cipher specification pattern detected in LUKS2 header."));
+		r = -EINVAL;
+		goto out;
+	}
+
 	if ((r = crypt_header_backup(cd, CRYPT_LUKS, rc->header_file_org)))
 		goto out;
 	if (isLUKS2(rc->type)) {