dm crypt: mark key as invalid until properly loaded

commit 265e9098bac02bc5e36cda21fdbad34cb5b2f48d upstream.

In crypt_set_key(), if a failure occurs while replacing the old key
(e.g. tfm->setkey() fails) the key must not have DM_CRYPT_KEY_VALID flag
set.  Otherwise, the crypto layer would have an invalid key that still
has DM_CRYPT_KEY_VALID flag set.

Signed-off-by: Ondrej Kozina <>
Reviewed-by: Mikulas Patocka <>
Signed-off-by: Mike Snitzer <>
Signed-off-by: Greg Kroah-Hartman <>

diff --git a/drivers/md/dm-crypt.c b/drivers/md/dm-crypt.c
index 5cac11d..de62888 100644
--- a/drivers/md/dm-crypt.c
+++ b/drivers/md/dm-crypt.c
@@ -1500,12 +1500,15 @@
 	if (!cc->key_size && strcmp(key, "-"))
 		goto out;
+	/* clear the flag since following operations may invalidate previously valid key */
+	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
 	if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
 		goto out;
-	set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
 	r = crypt_setkey_allcpus(cc);
+	if (!r)
+		set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
 	/* Hex key string not needed after here, so wipe it. */