Double-check secret EC point multiplications.

Doing a Jacobian point-on-curve check has negligible cost compared to
the point operations. We may as well perform one to add some defense
against potential bugs and such. (We already double-check RSA
operations.)

Before:
Did 40000 ECDH P-224 operations in 3014872us (13267.6 ops/sec)
Did 55000 ECDH P-256 operations in 3026351us (18173.7 ops/sec)
Did 3410 ECDH P-384 operations in 3053181us (1116.9 ops/sec)
Did 1364 ECDH P-521 operations in 3079656us (442.9 ops/sec)
Did 83000 ECDSA P-224 signing operations in 3013476us (27542.9 ops/sec)
Did 41000 ECDSA P-224 verify operations in 3073530us (13339.7 ops/sec)
Did 168000 ECDSA P-256 signing operations in 3008562us (55840.6 ops/sec)
Did 60000 ECDSA P-256 verify operations in 3038517us (19746.5 ops/sec)
Did 6169 ECDSA P-384 signing operations in 3066741us (2011.6 ops/sec)
Did 6231 ECDSA P-384 verify operations in 3054468us (2040.0 ops/sec)
Did 2418 ECDSA P-521 signing operations in 3058901us (790.5 ops/sec)
Did 2418 ECDSA P-521 verify operations in 3048765us (793.1 ops/sec)

After:
Did 39600 ECDH P-224 operations in 3001966us (13191.4 ops/sec)
Did 55000 ECDH P-256 operations in 3033098us (18133.3 ops/sec)
Did 3441 ECDH P-384 operations in 3088436us (1114.2 ops/sec)
Did 1364 ECDH P-521 operations in 3087711us (441.8 ops/sec)
Did 83000 ECDSA P-224 signing operations in 3029486us (27397.4 ops/sec)
Did 40000 ECDSA P-224 verify operations in 3005452us (13309.1 ops/sec)
Did 168000 ECDSA P-256 signing operations in 3011387us (55788.2 ops/sec)
Did 60000 ECDSA P-256 verify operations in 3030343us (19799.7 ops/sec)
Did 6076 ECDSA P-384 signing operations in 3023469us (2009.6 ops/sec)
Did 6231 ECDSA P-384 verify operations in 3056138us (2038.8 ops/sec)
Did 2418 ECDSA P-521 signing operations in 3057375us (790.9 ops/sec)
Did 2449 ECDSA P-521 verify operations in 3083418us (794.2 ops/sec)

Change-Id: Icedc51e340c8f3a21f96a535395814575e0c89b2
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/40592
Commit-Queue: David Benjamin <davidben@google.com>
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/fipsmodule/ec/ec.c b/crypto/fipsmodule/ec/ec.c
index 2fa1676..26e094d 100644
--- a/crypto/fipsmodule/ec/ec.c
+++ b/crypto/fipsmodule/ec/ec.c
@@ -1010,6 +1010,14 @@
   }
 
   group->meth->mul(group, r, p, scalar);
+
+  // Check the result is on the curve to defend against fault attacks or bugs.
+  // This has negligible cost compared to the multiplication.
+  if (!ec_GFp_simple_is_on_curve(group, r)) {
+    OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
+    return 0;
+  }
+
   return 1;
 }
 
@@ -1021,6 +1029,14 @@
   }
 
   group->meth->mul_base(group, r, scalar);
+
+  // Check the result is on the curve to defend against fault attacks or bugs.
+  // This has negligible cost compared to the multiplication.
+  if (!ec_GFp_simple_is_on_curve(group, r)) {
+    OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
+    return 0;
+  }
+
   return 1;
 }