From e191549317c08e340b9406bf2958868b1f119df2 Mon Sep 17 00:00:00 2001
From: Kai Ye <yekai13@huawei.com>
Date: Thu, 13 Jan 2022 16:33:37 +0800
Subject: [PATCH 44/53] cipher: add semi-weak keys checking

Add semi-weak keys checking based on OpenSSL. it will improve the
security of the system.

Signed-off-by: Kai Ye <yekai13@huawei.com>
---
 wd_cipher.c | 30 +++++++++++++++++++++++-------
 1 file changed, 23 insertions(+), 7 deletions(-)

diff --git a/wd_cipher.c b/wd_cipher.c
index 9c1f98c..85f7e65 100644
--- a/wd_cipher.c
+++ b/wd_cipher.c
@@ -19,15 +19,31 @@
 #define DES3_3KEY_SIZE		(3 * DES_KEY_SIZE)
 
 #define WD_POOL_MAX_ENTRIES	1024
-#define DES_WEAK_KEY_NUM	4
+#define DES_WEAK_KEY_NUM	16
 #define MAX_RETRY_COUNTS	200000000
 
 #define POLL_SIZE		100000
 #define POLL_TIME		1000
 
-static __u64 des_weak_key[DES_WEAK_KEY_NUM] = {
-	0x0101010101010101, 0xFEFEFEFEFEFEFEFE,
-	0xE0E0E0E0F1F1F1F1, 0x1F1F1F1F0E0E0E0E
+static const unsigned char des_weak_keys[DES_WEAK_KEY_NUM][DES_KEY_SIZE] = {
+	/* weak keys */
+	{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
+	{0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE},
+	{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E},
+	{0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1},
+	/* semi-weak keys */
+	{0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE},
+	{0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01},
+	{0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1},
+	{0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E},
+	{0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1},
+	{0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01},
+	{0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE},
+	{0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E},
+	{0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E},
+	{0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01},
+	{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE},
+	{0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1}
 };
 
 struct wd_cipher_setting {
@@ -81,12 +97,12 @@ void wd_cipher_set_driver(struct wd_cipher_driver *drv)
 	wd_cipher_setting.driver = drv;
 }
 
-static bool is_des_weak_key(const __u64 *key)
+static bool is_des_weak_key(const __u8 *key)
 {
 	int i;
 
 	for (i = 0; i < DES_WEAK_KEY_NUM; i++) {
-		if (*key == des_weak_key[i])
+		if (memcmp(des_weak_keys[i], key, DES_KEY_SIZE) == 0)
 			return true;
 	}
 
@@ -173,7 +189,7 @@ int wd_cipher_set_key(handle_t h_sess, const __u8 *key, __u32 key_len)
 		WD_ERR("cipher set key input key length err!\n");
 		return -WD_EINVAL;
 	}
-	if (sess->alg == WD_CIPHER_DES && is_des_weak_key((__u64 *)key)) {
+	if (sess->alg == WD_CIPHER_DES && is_des_weak_key(key)) {
 		WD_ERR("input des key is weak key!\n");
 		return -WD_EINVAL;
 	}
-- 
2.25.1

