crypto: des_generic - Forbid 2-key in 3DES and add helpers
authorHerbert Xu <herbert@gondor.apana.org.au>
Thu, 11 Apr 2019 08:50:56 +0000 (16:50 +0800)
committerHerbert Xu <herbert@gondor.apana.org.au>
Thu, 18 Apr 2019 14:14:58 +0000 (22:14 +0800)
This patch adds a requirement to the generic 3DES implementation
such that 2-key 3DES (K1 == K3) is no longer allowed in FIPS mode.

We will also provide helpers that may be used by drivers that
implement 3DES to make the same check.

Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
crypto/des_generic.c
include/crypto/des.h

index 1e66216..ebec1fb 100644 (file)
@@ -862,14 +862,11 @@ static void des_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
 int __des3_ede_setkey(u32 *expkey, u32 *flags, const u8 *key,
                      unsigned int keylen)
 {
-       const u32 *K = (const u32 *)key;
+       int err;
 
-       if (unlikely(!((K[0] ^ K[2]) | (K[1] ^ K[3])) ||
-                    !((K[2] ^ K[4]) | (K[3] ^ K[5]))) &&
-                    (*flags & CRYPTO_TFM_REQ_FORBID_WEAK_KEYS)) {
-               *flags |= CRYPTO_TFM_RES_WEAK_KEY;
-               return -EINVAL;
-       }
+       err = __des3_verify_key(flags, key);
+       if (unlikely(err))
+               return err;
 
        des_ekey(expkey, key); expkey += DES_EXPKEY_WORDS; key += DES_KEY_SIZE;
        dkey(expkey, key); expkey += DES_EXPKEY_WORDS; key += DES_KEY_SIZE;
index d4094d5..72c7c8e 100644 (file)
@@ -6,6 +6,11 @@
 #ifndef __CRYPTO_DES_H
 #define __CRYPTO_DES_H
 
+#include <crypto/skcipher.h>
+#include <linux/compiler.h>
+#include <linux/fips.h>
+#include <linux/string.h>
+
 #define DES_KEY_SIZE           8
 #define DES_EXPKEY_WORDS       32
 #define DES_BLOCK_SIZE         8
 #define DES3_EDE_EXPKEY_WORDS  (3 * DES_EXPKEY_WORDS)
 #define DES3_EDE_BLOCK_SIZE    DES_BLOCK_SIZE
 
+static inline int __des3_verify_key(u32 *flags, const u8 *key)
+{
+       int err = -EINVAL;
+       u32 K[6];
+
+       memcpy(K, key, DES3_EDE_KEY_SIZE);
+
+       if (unlikely(!((K[0] ^ K[2]) | (K[1] ^ K[3])) ||
+                    !((K[2] ^ K[4]) | (K[3] ^ K[5]))) &&
+                    (fips_enabled ||
+                     (*flags & CRYPTO_TFM_REQ_FORBID_WEAK_KEYS)))
+               goto bad;
+
+       if (unlikely(!((K[0] ^ K[4]) | (K[1] ^ K[5]))) && fips_enabled)
+               goto bad;
+
+       err = 0;
+
+out:
+       memzero_explicit(K, DES3_EDE_KEY_SIZE);
+
+       return err;
+
+bad:
+       *flags |= CRYPTO_TFM_RES_WEAK_KEY;
+       goto out;
+}
+
+static inline int des3_verify_key(struct crypto_skcipher *tfm, const u8 *key)
+{
+       u32 flags;
+       int err;
+
+       flags = crypto_skcipher_get_flags(tfm);
+       err = __des3_verify_key(&flags, key);
+       crypto_skcipher_set_flags(tfm, flags);
+       return err;
+}
 
 extern unsigned long des_ekey(u32 *pe, const u8 *k);