Don't crash when generating a key for a zero DH prime.

I didn't look into whether this was reachable, but I assume not. Still,
better to be robust here becasue DH groups are commonly under some
amount of attacker control.

Change-Id: I1e0c33ccf314c73a9d34dd48312f6f7580049ba7
Reviewed-on: https://boringssl-review.googlesource.com/10261
Reviewed-by: Adam Langley <agl@google.com>
Commit-Queue: Adam Langley <agl@google.com>
CQ-Verified: CQ bot account: commit-bot@chromium.org <commit-bot@chromium.org>
diff --git a/crypto/dh/dh.c b/crypto/dh/dh.c
index 91535c5..ec297c4 100644
--- a/crypto/dh/dh.c
+++ b/crypto/dh/dh.c
@@ -256,7 +256,6 @@
 int DH_generate_key(DH *dh) {
   int ok = 0;
   int generate_new_key = 0;
-  unsigned l;
   BN_CTX *ctx = NULL;
   BIGNUM *pub_key = NULL, *priv_key = NULL;
   BIGNUM local_priv;
@@ -302,8 +301,17 @@
       }
     } else {
       /* secret exponent length */
-      l = dh->priv_length ? dh->priv_length : BN_num_bits(dh->p) - 1;
-      if (!BN_rand(priv_key, l, 0, 0)) {
+      unsigned priv_bits = dh->priv_length;
+      if (priv_bits == 0) {
+        const unsigned p_bits = BN_num_bits(dh->p);
+        if (p_bits == 0) {
+          goto err;
+        }
+
+        priv_bits = p_bits - 1;
+      }
+
+      if (!BN_rand(priv_key, priv_bits, 0, 0)) {
         goto err;
       }
     }