dh key: get rid of stack allocated array
authorTycho Andersen <tycho@tycho.ws>
Tue, 24 Apr 2018 20:26:38 +0000 (14:26 -0600)
committerJames Morris <james.morris@microsoft.com>
Fri, 11 May 2018 20:07:47 +0000 (13:07 -0700)
We're interested in getting rid of all of the stack allocated arrays in the
kernel: https://lkml.org/lkml/2018/3/7/621

This particular vla is used as a temporary output buffer in case there is
too much hash output for the destination buffer. Instead, let's just
allocate a buffer that's big enough initially, but only copy back to
userspace the amount that was originally asked for.

v2: allocate enough in the original output buffer vs creating a temporary
    output buffer

Signed-off-by: Tycho Andersen <tycho@tycho.ws>
Reviewed-by: Kees Cook <keescook@chromium.org>
CC: David Howells <dhowells@redhat.com>
CC: James Morris <jmorris@namei.org>
CC: "Serge E. Hallyn" <serge@hallyn.com>
CC: Eric Biggers <ebiggers3@gmail.com>
Signed-off-by: James Morris <james.morris@microsoft.com>
security/keys/dh.c

index d1ea9f3..9fecaea 100644 (file)
@@ -183,24 +183,13 @@ static int kdf_ctr(struct kdf_sdesc *sdesc, const u8 *src, unsigned int slen,
                                goto err;
                }
 
-               if (dlen < h) {
-                       u8 tmpbuffer[h];
-
-                       err = crypto_shash_final(desc, tmpbuffer);
-                       if (err)
-                               goto err;
-                       memcpy(dst, tmpbuffer, dlen);
-                       memzero_explicit(tmpbuffer, h);
-                       return 0;
-               } else {
-                       err = crypto_shash_final(desc, dst);
-                       if (err)
-                               goto err;
+               err = crypto_shash_final(desc, dst);
+               if (err)
+                       goto err;
 
-                       dlen -= h;
-                       dst += h;
-                       counter = cpu_to_be32(be32_to_cpu(counter) + 1);
-               }
+               dlen -= h;
+               dst += h;
+               counter = cpu_to_be32(be32_to_cpu(counter) + 1);
        }
 
        return 0;
@@ -216,14 +205,16 @@ static int keyctl_dh_compute_kdf(struct kdf_sdesc *sdesc,
 {
        uint8_t *outbuf = NULL;
        int ret;
+       size_t outbuf_len = round_up(buflen,
+                                    crypto_shash_digestsize(sdesc->shash.tfm));
 
-       outbuf = kmalloc(buflen, GFP_KERNEL);
+       outbuf = kmalloc(outbuf_len, GFP_KERNEL);
        if (!outbuf) {
                ret = -ENOMEM;
                goto err;
        }
 
-       ret = kdf_ctr(sdesc, kbuf, kbuflen, outbuf, buflen, lzero);
+       ret = kdf_ctr(sdesc, kbuf, kbuflen, outbuf, outbuf_len, lzero);
        if (ret)
                goto err;