xref: /openbsd-src/lib/libcrypto/ecdsa/ecdsa.c (revision c0ee283e976ede249a34ca5fe4ce21ae8d60d09c)
1 /* $OpenBSD: ecdsa.c,v 1.2 2023/07/05 12:27:36 tb Exp $ */
2 /* ====================================================================
3  * Copyright (c) 2000-2002 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    licensing@OpenSSL.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55 
56 #include <string.h>
57 
58 #include <openssl/opensslconf.h>
59 
60 #include <openssl/asn1t.h>
61 #include <openssl/bn.h>
62 #include <openssl/err.h>
63 #include <openssl/evp.h>
64 #include <openssl/objects.h>
65 
66 #include "bn_local.h"
67 #include "ec_local.h"
68 #include "ecdsa_local.h"
69 
70 static const ASN1_TEMPLATE ECDSA_SIG_seq_tt[] = {
71 	{
72 		.flags = 0,
73 		.tag = 0,
74 		.offset = offsetof(ECDSA_SIG, r),
75 		.field_name = "r",
76 		.item = &BIGNUM_it,
77 	},
78 	{
79 		.flags = 0,
80 		.tag = 0,
81 		.offset = offsetof(ECDSA_SIG, s),
82 		.field_name = "s",
83 		.item = &BIGNUM_it,
84 	},
85 };
86 
87 const ASN1_ITEM ECDSA_SIG_it = {
88 	.itype = ASN1_ITYPE_SEQUENCE,
89 	.utype = V_ASN1_SEQUENCE,
90 	.templates = ECDSA_SIG_seq_tt,
91 	.tcount = sizeof(ECDSA_SIG_seq_tt) / sizeof(ASN1_TEMPLATE),
92 	.funcs = NULL,
93 	.size = sizeof(ECDSA_SIG),
94 	.sname = "ECDSA_SIG",
95 };
96 
97 ECDSA_SIG *ECDSA_SIG_new(void);
98 void ECDSA_SIG_free(ECDSA_SIG *a);
99 ECDSA_SIG *d2i_ECDSA_SIG(ECDSA_SIG **a, const unsigned char **in, long len);
100 int i2d_ECDSA_SIG(const ECDSA_SIG *a, unsigned char **out);
101 
102 ECDSA_SIG *
103 d2i_ECDSA_SIG(ECDSA_SIG **a, const unsigned char **in, long len)
104 {
105 	return (ECDSA_SIG *)ASN1_item_d2i((ASN1_VALUE **)a, in, len,
106 	    &ECDSA_SIG_it);
107 }
108 
109 int
110 i2d_ECDSA_SIG(const ECDSA_SIG *a, unsigned char **out)
111 {
112 	return ASN1_item_i2d((ASN1_VALUE *)a, out, &ECDSA_SIG_it);
113 }
114 
115 ECDSA_SIG *
116 ECDSA_SIG_new(void)
117 {
118 	return (ECDSA_SIG *)ASN1_item_new(&ECDSA_SIG_it);
119 }
120 
121 void
122 ECDSA_SIG_free(ECDSA_SIG *a)
123 {
124 	ASN1_item_free((ASN1_VALUE *)a, &ECDSA_SIG_it);
125 }
126 
127 void
128 ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
129 {
130 	if (pr != NULL)
131 		*pr = sig->r;
132 	if (ps != NULL)
133 		*ps = sig->s;
134 }
135 
136 const BIGNUM *
137 ECDSA_SIG_get0_r(const ECDSA_SIG *sig)
138 {
139 	return sig->r;
140 }
141 
142 const BIGNUM *
143 ECDSA_SIG_get0_s(const ECDSA_SIG *sig)
144 {
145 	return sig->s;
146 }
147 
148 int
149 ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s)
150 {
151 	if (r == NULL || s == NULL)
152 		return 0;
153 
154 	BN_free(sig->r);
155 	BN_free(sig->s);
156 	sig->r = r;
157 	sig->s = s;
158 	return 1;
159 }
160 
161 int
162 ECDSA_size(const EC_KEY *r)
163 {
164 	const EC_GROUP *group;
165 	const BIGNUM *order = NULL;
166 	ECDSA_SIG sig;
167 	int ret = 0;
168 
169 	if (r == NULL)
170 		goto err;
171 
172 	if ((group = EC_KEY_get0_group(r)) == NULL)
173 		goto err;
174 
175 	if ((order = EC_GROUP_get0_order(group)) == NULL)
176 		goto err;
177 
178 	sig.r = (BIGNUM *)order;
179 	sig.s = (BIGNUM *)order;
180 
181 	if ((ret = i2d_ECDSA_SIG(&sig, NULL)) < 0)
182 		ret = 0;
183 
184  err:
185 	return ret;
186 }
187 
188 /*
189  * FIPS 186-5, section 6.4.1, step 2: convert hashed message into an integer.
190  * Use the order_bits leftmost bits if it exceeds the group order.
191  */
192 static int
193 ecdsa_prepare_digest(const unsigned char *digest, int digest_len,
194     const EC_KEY *key, BIGNUM *e)
195 {
196 	const EC_GROUP *group;
197 	int digest_bits, order_bits;
198 
199 	if (!BN_bin2bn(digest, digest_len, e)) {
200 		ECDSAerror(ERR_R_BN_LIB);
201 		return 0;
202 	}
203 
204 	if ((group = EC_KEY_get0_group(key)) == NULL)
205 		return 0;
206 	order_bits = EC_GROUP_order_bits(group);
207 
208 	digest_bits = 8 * digest_len;
209 	if (digest_bits <= order_bits)
210 		return 1;
211 
212 	return BN_rshift(e, e, digest_bits - order_bits);
213 }
214 
215 int
216 ecdsa_sign(int type, const unsigned char *digest, int digest_len,
217     unsigned char *signature, unsigned int *signature_len, const BIGNUM *kinv,
218     const BIGNUM *r, EC_KEY *key)
219 {
220 	ECDSA_SIG *sig;
221 	int out_len = 0;
222 	int ret = 0;
223 
224 	if ((sig = ECDSA_do_sign_ex(digest, digest_len, kinv, r, key)) == NULL)
225 		goto err;
226 
227 	if ((out_len = i2d_ECDSA_SIG(sig, &signature)) < 0) {
228 		out_len = 0;
229 		goto err;
230 	}
231 
232 	ret = 1;
233 
234  err:
235 	*signature_len = out_len;
236 	ECDSA_SIG_free(sig);
237 
238 	return ret;
239 }
240 
241 /*
242  * FIPS 186-5, section 6.4.1, steps 3-8 and 11: Generate k, calculate r and
243  * kinv, and clear it. If r == 0, try again with a new random k.
244  */
245 
246 int
247 ecdsa_sign_setup(EC_KEY *key, BN_CTX *in_ctx, BIGNUM **out_kinv, BIGNUM **out_r)
248 {
249 	const EC_GROUP *group;
250 	EC_POINT *point = NULL;
251 	BN_CTX *ctx = NULL;
252 	BIGNUM *k = NULL, *r = NULL;
253 	const BIGNUM *order;
254 	BIGNUM *x;
255 	int order_bits;
256 	int ret = 0;
257 
258 	BN_free(*out_kinv);
259 	*out_kinv = NULL;
260 
261 	BN_free(*out_r);
262 	*out_r = NULL;
263 
264 	if (key == NULL) {
265 		ECDSAerror(ERR_R_PASSED_NULL_PARAMETER);
266 		goto err;
267 	}
268 	if ((group = EC_KEY_get0_group(key)) == NULL) {
269 		ECDSAerror(ERR_R_PASSED_NULL_PARAMETER);
270 		goto err;
271 	}
272 
273 	if ((k = BN_new()) == NULL)
274 		goto err;
275 	if ((r = BN_new()) == NULL)
276 		goto err;
277 
278 	if ((ctx = in_ctx) == NULL)
279 		ctx = BN_CTX_new();
280 	if (ctx == NULL) {
281 		ECDSAerror(ERR_R_MALLOC_FAILURE);
282 		goto err;
283 	}
284 
285 	BN_CTX_start(ctx);
286 
287 	if ((x = BN_CTX_get(ctx)) == NULL)
288 		goto err;
289 
290 	if ((point = EC_POINT_new(group)) == NULL) {
291 		ECDSAerror(ERR_R_EC_LIB);
292 		goto err;
293 	}
294 	if ((order = EC_GROUP_get0_order(group)) == NULL) {
295 		ECDSAerror(ERR_R_EC_LIB);
296 		goto err;
297 	}
298 
299 	if (BN_cmp(order, BN_value_one()) <= 0) {
300 		ECDSAerror(EC_R_INVALID_GROUP_ORDER);
301 		goto err;
302 	}
303 
304 	/* Reject curves with an order that is smaller than 80 bits. */
305 	if ((order_bits = BN_num_bits(order)) < 80) {
306 		ECDSAerror(EC_R_INVALID_GROUP_ORDER);
307 		goto err;
308 	}
309 
310 	/* Preallocate space. */
311 	if (!BN_set_bit(k, order_bits) ||
312 	    !BN_set_bit(r, order_bits) ||
313 	    !BN_set_bit(x, order_bits))
314 		goto err;
315 
316 	/* Step 11: repeat until r != 0. */
317 	do {
318 		/* Step 3: generate random k. */
319 		if (!bn_rand_interval(k, BN_value_one(), order)) {
320 			ECDSAerror(ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED);
321 			goto err;
322 		}
323 
324 		/*
325 		 * We do not want timing information to leak the length of k,
326 		 * so we compute G * k using an equivalent scalar of fixed
327 		 * bit-length.
328 		 *
329 		 * We unconditionally perform both of these additions to prevent
330 		 * a small timing information leakage.  We then choose the sum
331 		 * that is one bit longer than the order.  This guarantees the
332 		 * code path used in the constant time implementations
333 		 * elsewhere.
334 		 *
335 		 * TODO: revisit the bn_copy aiming for a memory access agnostic
336 		 * conditional copy.
337 		 */
338 		if (!BN_add(r, k, order) ||
339 		    !BN_add(x, r, order) ||
340 		    !bn_copy(k, BN_num_bits(r) > order_bits ? r : x))
341 			goto err;
342 
343 		BN_set_flags(k, BN_FLG_CONSTTIME);
344 
345 		/* Step 5: P = k * G. */
346 		if (!EC_POINT_mul(group, point, k, NULL, NULL, ctx)) {
347 			ECDSAerror(ERR_R_EC_LIB);
348 			goto err;
349 		}
350 		/* Steps 6 (and 7): from P = (x, y) retain the x-coordinate. */
351 		if (!EC_POINT_get_affine_coordinates(group, point, x, NULL,
352 		    ctx)) {
353 			ECDSAerror(ERR_R_EC_LIB);
354 			goto err;
355 		}
356 		/* Step 8: r = x (mod order). */
357 		if (!BN_nnmod(r, x, order, ctx)) {
358 			ECDSAerror(ERR_R_BN_LIB);
359 			goto err;
360 		}
361 	} while (BN_is_zero(r));
362 
363 	/* Step 4: calculate kinv. */
364 	if (BN_mod_inverse_ct(k, k, order, ctx) == NULL) {
365 		ECDSAerror(ERR_R_BN_LIB);
366 		goto err;
367 	}
368 
369 	*out_kinv = k;
370 	k = NULL;
371 
372 	*out_r = r;
373 	r = NULL;
374 
375 	ret = 1;
376 
377  err:
378 	BN_CTX_end(ctx);
379 	if (ctx != in_ctx)
380 		BN_CTX_free(ctx);
381 	BN_free(k);
382 	BN_free(r);
383 	EC_POINT_free(point);
384 
385 	return ret;
386 }
387 
388 /*
389  * FIPS 186-5, section 6.4.1, step 9: compute s = inv(k)(e + xr) mod order.
390  * In order to reduce the possibility of a side-channel attack, the following
391  * is calculated using a random blinding value b in [1, order):
392  * s = inv(b)(be + bxr)inv(k) mod order.
393  */
394 
395 static int
396 ecdsa_compute_s(BIGNUM **out_s, const BIGNUM *e, const BIGNUM *kinv,
397     const BIGNUM *r, const EC_KEY *key, BN_CTX *ctx)
398 {
399 	const EC_GROUP *group;
400 	const BIGNUM *order, *priv_key;
401 	BIGNUM *b, *binv, *be, *bxr;
402 	BIGNUM *s = NULL;
403 	int ret = 0;
404 
405 	*out_s = NULL;
406 
407 	BN_CTX_start(ctx);
408 
409 	if ((group = EC_KEY_get0_group(key)) == NULL) {
410 		ECDSAerror(ERR_R_PASSED_NULL_PARAMETER);
411 		goto err;
412 	}
413 	if ((order = EC_GROUP_get0_order(group)) == NULL) {
414 		ECDSAerror(ERR_R_EC_LIB);
415 		goto err;
416 	}
417 	if ((priv_key = EC_KEY_get0_private_key(key)) == NULL) {
418 		ECDSAerror(ERR_R_PASSED_NULL_PARAMETER);
419 		goto err;
420 	}
421 
422 	if ((b = BN_CTX_get(ctx)) == NULL)
423 		goto err;
424 	if ((binv = BN_CTX_get(ctx)) == NULL)
425 		goto err;
426 	if ((be = BN_CTX_get(ctx)) == NULL)
427 		goto err;
428 	if ((bxr = BN_CTX_get(ctx)) == NULL)
429 		goto err;
430 
431 	if ((s = BN_new()) == NULL)
432 		goto err;
433 
434 	/*
435 	 * In a valid ECDSA signature, r must be in [1, order). Since r can be
436 	 * caller provided - either directly or by replacing sign_setup() - we
437 	 * can't rely on this being the case.
438 	 */
439 	if (BN_cmp(r, BN_value_one()) < 0 || BN_cmp(r, order) >= 0) {
440 		ECDSAerror(ECDSA_R_BAD_SIGNATURE);
441 		goto err;
442 	}
443 
444 	if (!bn_rand_interval(b, BN_value_one(), order)) {
445 		ECDSAerror(ERR_R_BN_LIB);
446 		goto err;
447 	}
448 
449 	if (BN_mod_inverse_ct(binv, b, order, ctx) == NULL) {
450 		ECDSAerror(ERR_R_BN_LIB);
451 		goto err;
452 	}
453 
454 	if (!BN_mod_mul(bxr, b, priv_key, order, ctx)) {
455 		ECDSAerror(ERR_R_BN_LIB);
456 		goto err;
457 	}
458 	if (!BN_mod_mul(bxr, bxr, r, order, ctx)) {
459 		ECDSAerror(ERR_R_BN_LIB);
460 		goto err;
461 	}
462 	if (!BN_mod_mul(be, b, e, order, ctx)) {
463 		ECDSAerror(ERR_R_BN_LIB);
464 		goto err;
465 	}
466 	if (!BN_mod_add(s, be, bxr, order, ctx)) {
467 		ECDSAerror(ERR_R_BN_LIB);
468 		goto err;
469 	}
470 	/* s = b(e + xr)k^-1 */
471 	if (!BN_mod_mul(s, s, kinv, order, ctx)) {
472 		ECDSAerror(ERR_R_BN_LIB);
473 		goto err;
474 	}
475 	/* s = (e + xr)k^-1 */
476 	if (!BN_mod_mul(s, s, binv, order, ctx)) {
477 		ECDSAerror(ERR_R_BN_LIB);
478 		goto err;
479 	}
480 
481 	/* Step 11: if s == 0 start over. */
482 	if (!BN_is_zero(s)) {
483 		*out_s = s;
484 		s = NULL;
485 	}
486 
487 	ret = 1;
488 
489  err:
490 	BN_CTX_end(ctx);
491 	BN_free(s);
492 
493 	return ret;
494 }
495 
496 /*
497  * It is too expensive to check curve parameters on every sign operation.
498  * Instead, cap the number of retries. A single retry is very unlikely, so
499  * allowing 32 retries is amply enough.
500  */
501 #define ECDSA_MAX_SIGN_ITERATIONS		32
502 
503 /*
504  * FIPS 186-5: Section 6.4.1: ECDSA signature generation, steps 2-12.
505  * The caller provides the hash of the message, thus performs step 1.
506  * Step 10, zeroing k and kinv, is done by BN_free().
507  */
508 
509 ECDSA_SIG *
510 ecdsa_sign_sig(const unsigned char *digest, int digest_len,
511     const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *key)
512 {
513 	BN_CTX *ctx = NULL;
514 	BIGNUM *kinv = NULL, *r = NULL, *s = NULL;
515 	BIGNUM *e;
516 	int caller_supplied_values = 0;
517 	int attempts = 0;
518 	ECDSA_SIG *sig = NULL;
519 
520 	if ((ctx = BN_CTX_new()) == NULL) {
521 		ECDSAerror(ERR_R_MALLOC_FAILURE);
522 		goto err;
523 	}
524 
525 	BN_CTX_start(ctx);
526 
527 	if ((e = BN_CTX_get(ctx)) == NULL)
528 		goto err;
529 
530 	/* Step 2: convert hash into an integer. */
531 	if (!ecdsa_prepare_digest(digest, digest_len, key, e))
532 		goto err;
533 
534 	if (in_kinv != NULL && in_r != NULL) {
535 		/*
536 		 * Use the caller's kinv and r. Don't call ECDSA_sign_setup().
537 		 * If we're unable to compute a valid signature, the caller
538 		 * must provide new values.
539 		 */
540 		caller_supplied_values = 1;
541 
542 		if ((kinv = BN_dup(in_kinv)) == NULL) {
543 			ECDSAerror(ERR_R_MALLOC_FAILURE);
544 			goto err;
545 		}
546 		if ((r = BN_dup(in_r)) == NULL) {
547 			ECDSAerror(ERR_R_MALLOC_FAILURE);
548 			goto err;
549 		}
550 	}
551 
552 	do {
553 		/* Steps 3-8: calculate kinv and r. */
554 		if (!caller_supplied_values) {
555 			if (!ECDSA_sign_setup(key, ctx, &kinv, &r)) {
556 				ECDSAerror(ERR_R_ECDSA_LIB);
557 				goto err;
558 			}
559 		}
560 
561 		/*
562 		 * Steps 9 and 11: if s is non-NULL, we have a valid signature.
563 		 */
564 		if (!ecdsa_compute_s(&s, e, kinv, r, key, ctx))
565 			goto err;
566 		if (s != NULL)
567 			break;
568 
569 		if (caller_supplied_values) {
570 			ECDSAerror(ECDSA_R_NEED_NEW_SETUP_VALUES);
571 			goto err;
572 		}
573 
574 		if (++attempts > ECDSA_MAX_SIGN_ITERATIONS) {
575 			ECDSAerror(EC_R_WRONG_CURVE_PARAMETERS);
576 			goto err;
577 		}
578 	} while (1);
579 
580 	/* Step 12: output (r, s). */
581 	if ((sig = ECDSA_SIG_new()) == NULL) {
582 		ECDSAerror(ERR_R_MALLOC_FAILURE);
583 		goto err;
584 	}
585 	if (!ECDSA_SIG_set0(sig, r, s)) {
586 		ECDSA_SIG_free(sig);
587 		goto err;
588 	}
589 	r = NULL;
590 	s = NULL;
591 
592  err:
593 	BN_CTX_end(ctx);
594 	BN_CTX_free(ctx);
595 	BN_free(kinv);
596 	BN_free(r);
597 	BN_free(s);
598 
599 	return sig;
600 }
601 
602 int
603 ecdsa_verify(int type, const unsigned char *digest, int digest_len,
604     const unsigned char *sigbuf, int sig_len, EC_KEY *key)
605 {
606 	ECDSA_SIG *s;
607 	unsigned char *der = NULL;
608 	const unsigned char *p;
609 	int der_len = 0;
610 	int ret = -1;
611 
612 	if ((s = ECDSA_SIG_new()) == NULL)
613 		goto err;
614 
615 	p = sigbuf;
616 	if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL)
617 		goto err;
618 
619 	/* Ensure signature uses DER and doesn't have trailing garbage */
620 	if ((der_len = i2d_ECDSA_SIG(s, &der)) != sig_len)
621 		goto err;
622 	if (timingsafe_memcmp(sigbuf, der, der_len))
623 		goto err;
624 
625 	ret = ECDSA_do_verify(digest, digest_len, s, key);
626 
627  err:
628 	freezero(der, der_len);
629 	ECDSA_SIG_free(s);
630 
631 	return ret;
632 }
633 
634 /*
635  * FIPS 186-5, section 6.4.2: ECDSA signature verification.
636  * The caller provides us with the hash of the message, so has performed step 2.
637  */
638 
639 int
640 ecdsa_verify_sig(const unsigned char *digest, int digest_len,
641     const ECDSA_SIG *sig, EC_KEY *key)
642 {
643 	const EC_GROUP *group;
644 	const EC_POINT *pub_key;
645 	EC_POINT *point = NULL;
646 	const BIGNUM *order;
647 	BN_CTX *ctx = NULL;
648 	BIGNUM *e, *sinv, *u, *v, *x;
649 	int ret = -1;
650 
651 	if (key == NULL || sig == NULL) {
652 		ECDSAerror(ECDSA_R_MISSING_PARAMETERS);
653 		goto err;
654 	}
655 	if ((group = EC_KEY_get0_group(key)) == NULL) {
656 		ECDSAerror(ECDSA_R_MISSING_PARAMETERS);
657 		goto err;
658 	}
659 	if ((pub_key = EC_KEY_get0_public_key(key)) == NULL) {
660 		ECDSAerror(ECDSA_R_MISSING_PARAMETERS);
661 		goto err;
662 	}
663 
664 	if ((ctx = BN_CTX_new()) == NULL) {
665 		ECDSAerror(ERR_R_MALLOC_FAILURE);
666 		goto err;
667 	}
668 
669 	BN_CTX_start(ctx);
670 
671 	if ((e = BN_CTX_get(ctx)) == NULL)
672 		goto err;
673 	if ((sinv = BN_CTX_get(ctx)) == NULL)
674 		goto err;
675 	if ((u = BN_CTX_get(ctx)) == NULL)
676 		goto err;
677 	if ((v = BN_CTX_get(ctx)) == NULL)
678 		goto err;
679 	if ((x = BN_CTX_get(ctx)) == NULL)
680 		goto err;
681 
682 	if ((order = EC_GROUP_get0_order(group)) == NULL) {
683 		ECDSAerror(ERR_R_EC_LIB);
684 		goto err;
685 	}
686 
687 	/* Step 1: verify that r and s are in the range [1, order). */
688 	if (BN_cmp(sig->r, BN_value_one()) < 0 || BN_cmp(sig->r, order) >= 0) {
689 		ECDSAerror(ECDSA_R_BAD_SIGNATURE);
690 		ret = 0;
691 		goto err;
692 	}
693 	if (BN_cmp(sig->s, BN_value_one()) < 0 || BN_cmp(sig->s, order) >= 0) {
694 		ECDSAerror(ECDSA_R_BAD_SIGNATURE);
695 		ret = 0;
696 		goto err;
697 	}
698 
699 	/* Step 3: convert the hash into an integer. */
700 	if (!ecdsa_prepare_digest(digest, digest_len, key, e))
701 		goto err;
702 
703 	/* Step 4: compute the inverse of s modulo order. */
704 	if (BN_mod_inverse_ct(sinv, sig->s, order, ctx) == NULL) {
705 		ECDSAerror(ERR_R_BN_LIB);
706 		goto err;
707 	}
708 	/* Step 5: compute u = s^-1 * e and v = s^-1 * r (modulo order). */
709 	if (!BN_mod_mul(u, e, sinv, order, ctx)) {
710 		ECDSAerror(ERR_R_BN_LIB);
711 		goto err;
712 	}
713 	if (!BN_mod_mul(v, sig->r, sinv, order, ctx)) {
714 		ECDSAerror(ERR_R_BN_LIB);
715 		goto err;
716 	}
717 
718 	/*
719 	 * Steps 6 and 7: compute R = G * u + pub_key * v = (x, y). Reject if
720 	 * it's the point at infinity - getting affine coordinates fails. Keep
721 	 * the x coordinate.
722 	 */
723 	if ((point = EC_POINT_new(group)) == NULL) {
724 		ECDSAerror(ERR_R_MALLOC_FAILURE);
725 		goto err;
726 	}
727 	if (!EC_POINT_mul(group, point, u, pub_key, v, ctx)) {
728 		ECDSAerror(ERR_R_EC_LIB);
729 		goto err;
730 	}
731 	if (!EC_POINT_get_affine_coordinates(group, point, x, NULL, ctx)) {
732 		ECDSAerror(ERR_R_EC_LIB);
733 		goto err;
734 	}
735 	/* Step 8: convert x to a number in [0, order). */
736 	if (!BN_nnmod(x, x, order, ctx)) {
737 		ECDSAerror(ERR_R_BN_LIB);
738 		goto err;
739 	}
740 
741 	/* Step 9: the signature is valid iff the x-coordinate is equal to r. */
742 	ret = (BN_cmp(x, sig->r) == 0);
743 
744  err:
745 	BN_CTX_end(ctx);
746 	BN_CTX_free(ctx);
747 	EC_POINT_free(point);
748 
749 	return ret;
750 }
751 
752 ECDSA_SIG *
753 ECDSA_do_sign(const unsigned char *digest, int digest_len, EC_KEY *key)
754 {
755 	return ECDSA_do_sign_ex(digest, digest_len, NULL, NULL, key);
756 }
757 
758 ECDSA_SIG *
759 ECDSA_do_sign_ex(const unsigned char *digest, int digest_len,
760     const BIGNUM *kinv, const BIGNUM *out_r, EC_KEY *key)
761 {
762 	if (key->meth->sign_sig == NULL) {
763 		ECDSAerror(EVP_R_METHOD_NOT_SUPPORTED);
764 		return 0;
765 	}
766 	return key->meth->sign_sig(digest, digest_len, kinv, out_r, key);
767 }
768 
769 int
770 ECDSA_sign(int type, const unsigned char *digest, int digest_len,
771     unsigned char *signature, unsigned int *signature_len, EC_KEY *key)
772 {
773 	return ECDSA_sign_ex(type, digest, digest_len, signature, signature_len,
774 	    NULL, NULL, key);
775 }
776 
777 int
778 ECDSA_sign_ex(int type, const unsigned char *digest, int digest_len,
779     unsigned char *signature, unsigned int *signature_len, const BIGNUM *kinv,
780     const BIGNUM *r, EC_KEY *key)
781 {
782 	if (key->meth->sign == NULL) {
783 		ECDSAerror(EVP_R_METHOD_NOT_SUPPORTED);
784 		return 0;
785 	}
786 	return key->meth->sign(type, digest, digest_len, signature,
787 	    signature_len, kinv, r, key);
788 }
789 
790 int
791 ECDSA_sign_setup(EC_KEY *key, BN_CTX *in_ctx, BIGNUM **out_kinv,
792     BIGNUM **out_r)
793 {
794 	if (key->meth->sign_setup == NULL) {
795 		ECDSAerror(EVP_R_METHOD_NOT_SUPPORTED);
796 		return 0;
797 	}
798 	return key->meth->sign_setup(key, in_ctx, out_kinv, out_r);
799 }
800 
801 int
802 ECDSA_do_verify(const unsigned char *digest, int digest_len,
803     const ECDSA_SIG *sig, EC_KEY *key)
804 {
805 	if (key->meth->verify_sig == NULL) {
806 		ECDSAerror(EVP_R_METHOD_NOT_SUPPORTED);
807 		return 0;
808 	}
809 	return key->meth->verify_sig(digest, digest_len, sig, key);
810 }
811 
812 int
813 ECDSA_verify(int type, const unsigned char *digest, int digest_len,
814     const unsigned char *sigbuf, int sig_len, EC_KEY *key)
815 {
816 	if (key->meth->verify == NULL) {
817 		ECDSAerror(EVP_R_METHOD_NOT_SUPPORTED);
818 		return 0;
819 	}
820 	return key->meth->verify(type, digest, digest_len, sigbuf, sig_len, key);
821 }
822