1/* ====================================================================
2 * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in
13 *    the documentation and/or other materials provided with the
14 *    distribution.
15 *
16 * 3. All advertising materials mentioning features or use of this
17 *    software must display the following acknowledgment:
18 *    "This product includes software developed by the OpenSSL Project
19 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
20 *
21 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22 *    endorse or promote products derived from this software without
23 *    prior written permission. For written permission, please contact
24 *    openssl-core@OpenSSL.org.
25 *
26 * 5. Products derived from this software may not be called "OpenSSL"
27 *    nor may "OpenSSL" appear in their names without prior written
28 *    permission of the OpenSSL Project.
29 *
30 * 6. Redistributions of any form whatsoever must retain the following
31 *    acknowledgment:
32 *    "This product includes software developed by the OpenSSL Project
33 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
48 *
49 * This product includes cryptographic software written by Eric Young
50 * (eay@cryptsoft.com).  This product includes software written by Tim
51 * Hudson (tjh@cryptsoft.com). */
52
53#include <openssl/ecdsa.h>
54
55#include <assert.h>
56#include <string.h>
57
58#include <openssl/bn.h>
59#include <openssl/bytestring.h>
60#include <openssl/err.h>
61#include <openssl/mem.h>
62
63#include "../ec/internal.h"
64
65
66int ECDSA_sign(int type, const uint8_t *digest, size_t digest_len, uint8_t *sig,
67               unsigned int *sig_len, EC_KEY *eckey) {
68  if (eckey->ecdsa_meth && eckey->ecdsa_meth->sign) {
69    return eckey->ecdsa_meth->sign(digest, digest_len, sig, sig_len, eckey);
70  }
71
72  return ECDSA_sign_ex(type, digest, digest_len, sig, sig_len, NULL, NULL,
73                       eckey);
74}
75
76int ECDSA_verify(int type, const uint8_t *digest, size_t digest_len,
77                 const uint8_t *sig, size_t sig_len, EC_KEY *eckey) {
78  ECDSA_SIG *s;
79  int ret = 0;
80  uint8_t *der = NULL;
81
82  if (eckey->ecdsa_meth && eckey->ecdsa_meth->verify) {
83    return eckey->ecdsa_meth->verify(digest, digest_len, sig, sig_len, eckey);
84  }
85
86  /* Decode the ECDSA signature. */
87  s = ECDSA_SIG_from_bytes(sig, sig_len);
88  if (s == NULL) {
89    goto err;
90  }
91
92  /* Defend against potential laxness in the DER parser. */
93  size_t der_len;
94  if (!ECDSA_SIG_to_bytes(&der, &der_len, s) ||
95      der_len != sig_len || memcmp(sig, der, sig_len) != 0) {
96    /* This should never happen. crypto/bytestring is strictly DER. */
97    OPENSSL_PUT_ERROR(ECDSA, ERR_R_INTERNAL_ERROR);
98    goto err;
99  }
100
101  ret = ECDSA_do_verify(digest, digest_len, s, eckey);
102
103err:
104  OPENSSL_free(der);
105  ECDSA_SIG_free(s);
106  return ret;
107}
108
109/* digest_to_bn interprets |digest_len| bytes from |digest| as a big-endian
110 * number and sets |out| to that value. It then truncates |out| so that it's,
111 * at most, as long as |order|. It returns one on success and zero otherwise. */
112static int digest_to_bn(BIGNUM *out, const uint8_t *digest, size_t digest_len,
113                        const BIGNUM *order) {
114  size_t num_bits;
115
116  num_bits = BN_num_bits(order);
117  /* Need to truncate digest if it is too long: first truncate whole
118   * bytes. */
119  if (8 * digest_len > num_bits) {
120    digest_len = (num_bits + 7) / 8;
121  }
122  if (!BN_bin2bn(digest, digest_len, out)) {
123    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
124    return 0;
125  }
126
127  /* If still too long truncate remaining bits with a shift */
128  if ((8 * digest_len > num_bits) &&
129      !BN_rshift(out, out, 8 - (num_bits & 0x7))) {
130    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
131    return 0;
132  }
133
134  return 1;
135}
136
137ECDSA_SIG *ECDSA_do_sign(const uint8_t *digest, size_t digest_len,
138                         EC_KEY *key) {
139  return ECDSA_do_sign_ex(digest, digest_len, NULL, NULL, key);
140}
141
142int ECDSA_do_verify(const uint8_t *digest, size_t digest_len,
143                    const ECDSA_SIG *sig, EC_KEY *eckey) {
144  int ret = 0;
145  BN_CTX *ctx;
146  BIGNUM *u1, *u2, *m, *X;
147  EC_POINT *point = NULL;
148  const EC_GROUP *group;
149  const EC_POINT *pub_key;
150
151  if (eckey->ecdsa_meth && eckey->ecdsa_meth->verify) {
152    OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED);
153    return 0;
154  }
155
156  /* check input values */
157  if ((group = EC_KEY_get0_group(eckey)) == NULL ||
158      (pub_key = EC_KEY_get0_public_key(eckey)) == NULL ||
159      sig == NULL) {
160    OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_MISSING_PARAMETERS);
161    return 0;
162  }
163
164  ctx = BN_CTX_new();
165  if (!ctx) {
166    OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
167    return 0;
168  }
169  BN_CTX_start(ctx);
170  u1 = BN_CTX_get(ctx);
171  u2 = BN_CTX_get(ctx);
172  m = BN_CTX_get(ctx);
173  X = BN_CTX_get(ctx);
174  if (u1 == NULL || u2 == NULL || m == NULL || X == NULL) {
175    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
176    goto err;
177  }
178
179  const BIGNUM *order = EC_GROUP_get0_order(group);
180  if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
181      BN_ucmp(sig->r, order) >= 0 || BN_is_zero(sig->s) ||
182      BN_is_negative(sig->s) || BN_ucmp(sig->s, order) >= 0) {
183    OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_BAD_SIGNATURE);
184    ret = 0; /* signature is invalid */
185    goto err;
186  }
187  /* calculate tmp1 = inv(S) mod order */
188  if (!BN_mod_inverse(u2, sig->s, order, ctx)) {
189    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
190    goto err;
191  }
192  if (!digest_to_bn(m, digest, digest_len, order)) {
193    goto err;
194  }
195  /* u1 = m * tmp mod order */
196  if (!BN_mod_mul(u1, m, u2, order, ctx)) {
197    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
198    goto err;
199  }
200  /* u2 = r * w mod q */
201  if (!BN_mod_mul(u2, sig->r, u2, order, ctx)) {
202    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
203    goto err;
204  }
205
206  point = EC_POINT_new(group);
207  if (point == NULL) {
208    OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
209    goto err;
210  }
211  if (!EC_POINT_mul(group, point, u1, pub_key, u2, ctx)) {
212    OPENSSL_PUT_ERROR(ECDSA, ERR_R_EC_LIB);
213    goto err;
214  }
215  if (!EC_POINT_get_affine_coordinates_GFp(group, point, X, NULL, ctx)) {
216    OPENSSL_PUT_ERROR(ECDSA, ERR_R_EC_LIB);
217    goto err;
218  }
219  if (!BN_nnmod(u1, X, order, ctx)) {
220    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
221    goto err;
222  }
223  /* if the signature is correct u1 is equal to sig->r */
224  ret = (BN_ucmp(u1, sig->r) == 0);
225
226err:
227  BN_CTX_end(ctx);
228  BN_CTX_free(ctx);
229  EC_POINT_free(point);
230  return ret;
231}
232
233static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp,
234                            BIGNUM **rp, const uint8_t *digest,
235                            size_t digest_len) {
236  BN_CTX *ctx = NULL;
237  BIGNUM *k = NULL, *r = NULL, *X = NULL;
238  EC_POINT *tmp_point = NULL;
239  const EC_GROUP *group;
240  int ret = 0;
241
242  if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL) {
243    OPENSSL_PUT_ERROR(ECDSA, ERR_R_PASSED_NULL_PARAMETER);
244    return 0;
245  }
246
247  if (ctx_in == NULL) {
248    if ((ctx = BN_CTX_new()) == NULL) {
249      OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
250      return 0;
251    }
252  } else {
253    ctx = ctx_in;
254  }
255
256  k = BN_new(); /* this value is later returned in *kinvp */
257  r = BN_new(); /* this value is later returned in *rp    */
258  X = BN_new();
259  if (k == NULL || r == NULL || X == NULL) {
260    OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
261    goto err;
262  }
263  tmp_point = EC_POINT_new(group);
264  if (tmp_point == NULL) {
265    OPENSSL_PUT_ERROR(ECDSA, ERR_R_EC_LIB);
266    goto err;
267  }
268
269  const BIGNUM *order = EC_GROUP_get0_order(group);
270
271  do {
272    /* If possible, we'll include the private key and message digest in the k
273     * generation. The |digest| argument is only empty if |ECDSA_sign_setup| is
274     * being used. */
275    do {
276      int ok;
277
278      if (digest_len > 0) {
279        ok = BN_generate_dsa_nonce(k, order, EC_KEY_get0_private_key(eckey),
280                                   digest, digest_len, ctx);
281      } else {
282        ok = BN_rand_range(k, order);
283      }
284      if (!ok) {
285        OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED);
286        goto err;
287      }
288    } while (BN_is_zero(k));
289
290    /* We do not want timing information to leak the length of k,
291     * so we compute G*k using an equivalent scalar of fixed
292     * bit-length. */
293
294    if (!BN_add(k, k, order)) {
295      goto err;
296    }
297    if (BN_num_bits(k) <= BN_num_bits(order)) {
298      if (!BN_add(k, k, order)) {
299        goto err;
300      }
301    }
302
303    /* compute r the x-coordinate of generator * k */
304    if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx)) {
305      OPENSSL_PUT_ERROR(ECDSA, ERR_R_EC_LIB);
306      goto err;
307    }
308    if (!EC_POINT_get_affine_coordinates_GFp(group, tmp_point, X, NULL, ctx)) {
309      OPENSSL_PUT_ERROR(ECDSA, ERR_R_EC_LIB);
310      goto err;
311    }
312
313    if (!BN_nnmod(r, X, order, ctx)) {
314      OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
315      goto err;
316    }
317  } while (BN_is_zero(r));
318
319  /* compute the inverse of k */
320  if (ec_group_get_mont_data(group) != NULL) {
321    /* We want inverse in constant time, therefore we use that the order must
322     * be prime and thus we can use Fermat's Little Theorem. */
323    if (!BN_set_word(X, 2) ||
324        !BN_sub(X, order, X)) {
325      OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
326      goto err;
327    }
328    BN_set_flags(X, BN_FLG_CONSTTIME);
329    if (!BN_mod_exp_mont_consttime(k, k, X, order, ctx,
330                                   ec_group_get_mont_data(group))) {
331      OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
332      goto err;
333    }
334  } else if (!BN_mod_inverse(k, k, order, ctx)) {
335    OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
336    goto err;
337  }
338  /* clear old values if necessary */
339  BN_clear_free(*rp);
340  BN_clear_free(*kinvp);
341
342  /* save the pre-computed values  */
343  *rp = r;
344  *kinvp = k;
345  ret = 1;
346
347err:
348  if (!ret) {
349    BN_clear_free(k);
350    BN_clear_free(r);
351  }
352  if (ctx_in == NULL) {
353    BN_CTX_free(ctx);
354  }
355  EC_POINT_free(tmp_point);
356  BN_clear_free(X);
357  return ret;
358}
359
360int ECDSA_sign_setup(EC_KEY *eckey, BN_CTX *ctx, BIGNUM **kinv, BIGNUM **rp) {
361  return ecdsa_sign_setup(eckey, ctx, kinv, rp, NULL, 0);
362}
363
364ECDSA_SIG *ECDSA_do_sign_ex(const uint8_t *digest, size_t digest_len,
365                            const BIGNUM *in_kinv, const BIGNUM *in_r,
366                            EC_KEY *eckey) {
367  int ok = 0;
368  BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL;
369  const BIGNUM *ckinv;
370  BN_CTX *ctx = NULL;
371  const EC_GROUP *group;
372  ECDSA_SIG *ret;
373  const BIGNUM *priv_key;
374
375  if (eckey->ecdsa_meth && eckey->ecdsa_meth->sign) {
376    OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED);
377    return NULL;
378  }
379
380  group = EC_KEY_get0_group(eckey);
381  priv_key = EC_KEY_get0_private_key(eckey);
382
383  if (group == NULL || priv_key == NULL) {
384    OPENSSL_PUT_ERROR(ECDSA, ERR_R_PASSED_NULL_PARAMETER);
385    return NULL;
386  }
387
388  ret = ECDSA_SIG_new();
389  if (!ret) {
390    OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
391    return NULL;
392  }
393  s = ret->s;
394
395  if ((ctx = BN_CTX_new()) == NULL ||
396      (tmp = BN_new()) == NULL ||
397      (m = BN_new()) == NULL) {
398    OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
399    goto err;
400  }
401
402  const BIGNUM *order = EC_GROUP_get0_order(group);
403
404  if (!digest_to_bn(m, digest, digest_len, order)) {
405    goto err;
406  }
407  for (;;) {
408    if (in_kinv == NULL || in_r == NULL) {
409      if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, digest, digest_len)) {
410        OPENSSL_PUT_ERROR(ECDSA, ERR_R_ECDSA_LIB);
411        goto err;
412      }
413      ckinv = kinv;
414    } else {
415      ckinv = in_kinv;
416      if (BN_copy(ret->r, in_r) == NULL) {
417        OPENSSL_PUT_ERROR(ECDSA, ERR_R_MALLOC_FAILURE);
418        goto err;
419      }
420    }
421
422    if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) {
423      OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
424      goto err;
425    }
426    if (!BN_mod_add_quick(s, tmp, m, order)) {
427      OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
428      goto err;
429    }
430    if (!BN_mod_mul(s, s, ckinv, order, ctx)) {
431      OPENSSL_PUT_ERROR(ECDSA, ERR_R_BN_LIB);
432      goto err;
433    }
434    if (BN_is_zero(s)) {
435      /* if kinv and r have been supplied by the caller
436       * don't to generate new kinv and r values */
437      if (in_kinv != NULL && in_r != NULL) {
438        OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NEED_NEW_SETUP_VALUES);
439        goto err;
440      }
441    } else {
442      /* s != 0 => we have a valid signature */
443      break;
444    }
445  }
446
447  ok = 1;
448
449err:
450  if (!ok) {
451    ECDSA_SIG_free(ret);
452    ret = NULL;
453  }
454  BN_CTX_free(ctx);
455  BN_clear_free(m);
456  BN_clear_free(tmp);
457  BN_clear_free(kinv);
458  return ret;
459}
460
461int ECDSA_sign_ex(int type, const uint8_t *digest, size_t digest_len,
462                  uint8_t *sig, unsigned int *sig_len, const BIGNUM *kinv,
463                  const BIGNUM *r, EC_KEY *eckey) {
464  int ret = 0;
465  ECDSA_SIG *s = NULL;
466
467  if (eckey->ecdsa_meth && eckey->ecdsa_meth->sign) {
468    OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_NOT_IMPLEMENTED);
469    *sig_len = 0;
470    goto err;
471  }
472
473  s = ECDSA_do_sign_ex(digest, digest_len, kinv, r, eckey);
474  if (s == NULL) {
475    *sig_len = 0;
476    goto err;
477  }
478
479  CBB cbb;
480  CBB_zero(&cbb);
481  size_t len;
482  if (!CBB_init_fixed(&cbb, sig, ECDSA_size(eckey)) ||
483      !ECDSA_SIG_marshal(&cbb, s) ||
484      !CBB_finish(&cbb, NULL, &len)) {
485    OPENSSL_PUT_ERROR(ECDSA, ECDSA_R_ENCODE_ERROR);
486    CBB_cleanup(&cbb);
487    *sig_len = 0;
488    goto err;
489  }
490  *sig_len = (unsigned)len;
491  ret = 1;
492
493err:
494  ECDSA_SIG_free(s);
495  return ret;
496}
497