Debian Codegraph @

cipher/ecc.c

raw
1 /* ecc.c - Elliptic Curve Cryptography
2 * Copyright (C) 2007, 2008, 2010, 2011 Free Software Foundation, Inc.
3 * Copyright (C) 2013, 2015 g10 Code GmbH
4 *
5 * This file is part of Libgcrypt.
6 *
7 * Libgcrypt is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * Libgcrypt is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /* This code is originally based on the Patch 0.1.6 for the gnupg
22 1.4.x branch as retrieved on 2007-03-21 from
23 http://www.calcurco.cat/eccGnuPG/src/gnupg-1.4.6-ecc0.2.0beta1.diff.bz2
24 The original authors are:
25 Written by
26 Sergi Blanch i Torne <d4372211 at alumnes.eup.udl.es>,
27 Ramiro Moreno Chiral <ramiro at eup.udl.es>
28 Maintainers
29 Sergi Blanch i Torne
30 Ramiro Moreno Chiral
31 Mikael Mylnikov (mmr)
32 For use in Libgcrypt the code has been heavily modified and cleaned
33 up. In fact there is not much left of the originally code except for
34 some variable names and the text book implementaion of the sign and
35 verification algorithms. The arithmetic functions have entirely
36 been rewritten and moved to mpi/ec.c.
37
38 ECDH encrypt and decrypt code written by Andrey Jivsov.
39 */
40
41
42 /* TODO:
43
44 - In mpi/ec.c we use mpi_powm for x^2 mod p: Either implement a
45 special case in mpi_powm or check whether mpi_mulm is faster.
46
47 */
48
49
50 #include <config.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <errno.h>
55
56 #include "g10lib.h"
57 #include "mpi.h"
58 #include "cipher.h"
59 #include "context.h"
60 #include "ec-context.h"
61 #include "pubkey-internal.h"
62 #include "ecc-common.h"
63
64
65 static const char *ecc_names[] =
66 {
67 "ecc",
68 "ecdsa",
69 "ecdh",
70 "eddsa",
71 "gost",
72 "sm2",
73 NULL,
74 };
75
76
77 /* Sample NIST P-256 key from RFC 6979 A.2.5 */
78 static const char ecdsa_sample_public_key_secp256[] =
79 "(public-key"
80 " (ecc"
81 " (curve secp256r1)"
82 " (q #04"
83 /**/ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6"
84 /**/ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299#)))";
85
86 static const char ecdsa_sample_secret_key_secp256[] =
87 "(private-key"
88 " (ecc"
89 " (curve secp256r1)"
90 " (d #C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721#)"
91 " (q #04"
92 /**/ "60FED4BA255A9D31C961EB74C6356D68C049B8923B61FA6CE669622E60F29FB6"
93 /**/ "7903FE1008B8BC99A41AE9E95628BC64F2F1B20C2D7E9F5177A3C294D4462299#)))";
94
95 /* Sample data from RFC 6979 section A.2.5, hash is of message "sample" */
96 static const char rfc6979_ecdsa_sample_data[] =
97 "(data (flags rfc6979 prehash)"
98 " (hash-algo sha256)"
99 " (value 6:sample))";
100
101 static const char rfc6979_ecdsa_sample_data_bad[] =
102 "(data (flags rfc6979)"
103 " (hash sha256 #bf2bdbe1aa9b6ec1e2ade1d694f41fc71a831d0268e98915"
104 /**/ "62113d8a62add1bf#))";
105
106 static const char *rfc6979_ecdsa_data_tmpl =
107 "(data (flags rfc6979)"
108 " (hash %s %b))";
109
110 /*
111 * Sample data from RFC 6979 section A.2.5, with fixed k,
112 * hash is of message "sample".
113 */
114 static const char ecdsa_sample_data[] =
115 "(data (flags raw prehash)"
116 " (label #A6E3C57DD01ABE90086538398355DD4C3B17AA873382B0F24D6129493D8AAD60#)"
117 " (hash-algo sha256)"
118 " (value 6:sample))";
119
120 static const char ecdsa_sample_data_bad[] =
121 "(data (flags raw)"
122 " (label #A6E3C57DD01ABE90086538398355DD4C3B17AA873382B0F24D6129493D8AAD60#)"
123 " (hash sha256 #bf2bdbe1aa9b6ec1e2ade1d694f41fc71a831d0268e98915"
124 /**/ "62113d8a62add1bf#))";
125
126 static const char *ecdsa_data_tmpl =
127 "(data (flags raw)"
128 " (label #A6E3C57DD01ABE90086538398355DD4C3B17AA873382B0F24D6129493D8AAD60#)"
129 " (hash %s %b))";
130
131 static const char ecdsa_signature_r[] =
132 "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716";
133
134 static const char ecdsa_signature_s[] =
135 "f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8";
136
137 /* Sample data from RFC 6979 section A.2.5, hash is of message "sample" */
138 static const char ecdsa_sample_data_string[] = "sample";
139 static const char ecdsa_sample_data_bad_string[] = "sbmple";
140
141
142 /* Ed25519 test vector from RFC 8032 7.1. */
143 static const char ed25519_sample_public_key[] =
144 "(public-key"
145 " (ecc"
146 " (curve Ed25519)"
147 " (flags eddsa)"
148 " (q #3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c#)))";
149 static const char ed25519_sample_secret_key[] =
150 "(private-key"
151 " (ecc"
152 " (curve Ed25519)"
153 " (flags eddsa)"
154 " (d #4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb#)"
155 " (q #3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c#)))";
156 static const char ed25519_sample_data[] =
157 "(data (value #72#))";
158 static const char ed25519_sample_data_bad[] =
159 "(data (value #72727272#))";
160 static const char ed25519_signature_r[] =
161 "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da";
162 static const char ed25519_signature_s[] =
163 "085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00";
164 static const char *ed25519_data_tmpl = "(data (value %b))";
165 /* Sample data from RFC 6979 section A.2.5, hash is of message "sample" */
166 static const char ed25519_sample_data_string[] = "\x72";
167 static const char ed25519_sample_data_bad_string[] = "\x72\x72\x72\x72";
168
169
170 /* Ed448 test vector from RFC 8032 7.4. */
171 static const char ed448_sample_public_key[] =
172 "(public-key"
173 " (ecc"
174 " (curve Ed448)"
175 " (q #43ba28f430cdff456ae531545f7ecd0ac834a55d9358c0372bfa0c6c6798c086"
176 /**/ "6aea01eb00742802b8438ea4cb82169c235160627b4c3a9480#)))";
177 static const char ed448_sample_secret_key[] =
178 "(private-key"
179 " (ecc"
180 " (curve Ed448)"
181 " (d #c4eab05d357007c632f3dbb48489924d552b08fe0c353a0d4a1f00acda2c463a"
182 /**/ "fbea67c5e8d2877c5e3bc397a659949ef8021e954e0a12274e#)"
183 " (q #43ba28f430cdff456ae531545f7ecd0ac834a55d9358c0372bfa0c6c6798c086"
184 /**/ "6aea01eb00742802b8438ea4cb82169c235160627b4c3a9480#)))";
185 static const char ed448_sample_data[] =
186 "(data (value #03#))";
187 static const char ed448_sample_data_bad[] =
188 "(data (value #030303#))";
189 static const char ed448_signature_r[] =
190 "26b8f91727bd62897af15e41eb43c377efb9c610d48f2335cb0bd0087810f435"
191 "2541b143c4b981b7e18f62de8ccdf633fc1bf037ab7cd77980";
192 static const char ed448_signature_s[] =
193 "5e0dbcc0aae1cbcee1afb2e027df36bc04dcecbf154336c19f0af7e0a6472905"
194 "e799f1953d2a0ff3348ab21aa4adafd1d234441cf807c03a00";
195 static const char *ed448_data_tmpl = "(data (value %b))";
196 /* Sample data from RFC 6979 section A.2.5, hash is of message "sample" */
197 static const char ed448_sample_data_string[] = "\x03";
198 static const char ed448_sample_data_bad_string[] = "\x03\x03\x03";
199
200
201 /* Registered progress function and its callback value. */
202 static void (*progress_cb) (void *, const char*, int, int, int);
203 static void *progress_cb_data;
204
205
206
207 /* Local prototypes. */
208 static void test_keys (mpi_ec_t ec, unsigned int nbits);
209 static int test_keys_fips (gcry_sexp_t skey);
210 static void test_ecdh_only_keys (mpi_ec_t ec, unsigned int nbits, int flags);
211 static unsigned int ecc_get_nbits (gcry_sexp_t parms);
212
213
214
215
216 void
217 _gcry_register_pk_ecc_progress (void (*cb) (void *, const char *,
218 int, int, int),
219 void *cb_data)
220 {
221 progress_cb = cb;
222 progress_cb_data = cb_data;
223 }
224
225 /* static void */
226 /* progress (int c) */
227 /* { */
228 /* if (progress_cb) */
229 /* progress_cb (progress_cb_data, "pk_ecc", c, 0, 0); */
230 /* } */
231
232
233
234 /**
235 * nist_generate_key - Standard version of the ECC key generation.
236 * @ec: Elliptic curve computation context.
237 * @flags: Flags controlling aspects of the creation.
238 * @r_x: On success this receives an allocated MPI with the affine
239 * x-coordinate of the poblic key. On error NULL is stored.
240 * @r_y: Ditto for the y-coordinate.
241 *
242 * Return: An error code.
243 *
244 * The @flags bits used by this function are %PUBKEY_FLAG_TRANSIENT to
245 * use a faster RNG, and %PUBKEY_FLAG_NO_KEYTEST to skip the assertion
246 * that the key works as expected.
247 *
248 * FIXME: Check whether N is needed.
249 */
250 static gpg_err_code_t
251 nist_generate_key (mpi_ec_t ec, int flags,
252 gcry_mpi_t *r_x, gcry_mpi_t *r_y)
253 {
254 mpi_point_struct Q;
255 gcry_random_level_t random_level;
256 gcry_mpi_t x, y;
257 const unsigned int pbits = ec->nbits;
258
259 point_init (&Q, ec->nbits);
260
261 if ((flags & PUBKEY_FLAG_TRANSIENT_KEY))
262 random_level = GCRY_STRONG_RANDOM;
263 else
264 random_level = GCRY_VERY_STRONG_RANDOM;
265
266 /* Generate a secret. */
267 if (ec->dialect == ECC_DIALECT_ED25519
268 || ec->dialect == ECC_DIALECT_SAFECURVE
269 || (flags & PUBKEY_FLAG_DJB_TWEAK))
270 {
271 char *rndbuf;
272 int len = (pbits+7)/8;
273
274 rndbuf = _gcry_random_bytes_secure (len, random_level);
275 if (ec->dialect == ECC_DIALECT_SAFECURVE)
276 ec->d = mpi_set_opaque (NULL, rndbuf, len*8);
277 else
278 {
279 ec->d = mpi_snew (pbits);
280 if ((pbits % 8))
281 rndbuf[0] &= (1 << (pbits % 8)) - 1;
282 rndbuf[0] |= (1 << ((pbits + 7) % 8));
283 rndbuf[len-1] &= (256 - ec->h);
284 _gcry_mpi_set_buffer (ec->d, rndbuf, len, 0);
285 xfree (rndbuf);
286 }
287 }
288 else
289 ec->d = _gcry_dsa_gen_k (ec->n, random_level);
290
291 /* Compute Q. */
292 _gcry_mpi_ec_mul_point (&Q, ec->d, ec->G, ec);
293
294 x = mpi_new (pbits);
295 if (r_y == NULL)
296 y = NULL;
297 else
298 y = mpi_new (pbits);
299 if (_gcry_mpi_ec_get_affine (x, y, &Q, ec))
300 log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "Q");
301
302 /* We want the Q=(x,y) be a "compliant key" in terms of the
303 * http://tools.ietf.org/html/draft-jivsov-ecc-compact, which simply
304 * means that we choose either Q=(x,y) or -Q=(x,p-y) such that we
305 * end up with the min(y,p-y) as the y coordinate. Such a public
306 * key allows the most efficient compression: y can simply be
307 * dropped because we know that it's a minimum of the two
308 * possibilities without any loss of security. Note that we don't
309 * do that for Ed25519 so that we do not violate the special
310 * construction of the secret key. */
311 if (r_y == NULL || ec->dialect == ECC_DIALECT_ED25519)
312 ec->Q = mpi_point_set (NULL, Q.x, Q.y, Q.z);
313 else
314 {
315 gcry_mpi_t negative;
316
317 negative = mpi_new (pbits);
318
319 if (ec->model == MPI_EC_WEIERSTRASS)
320 mpi_sub (negative, ec->p, y); /* negative = p - y */
321 else
322 mpi_sub (negative, ec->p, x); /* negative = p - x */
323
324 if (mpi_cmp (negative, y) < 0) /* p - y < p */
325 {
326 /* We need to end up with -Q; this assures that new Q's y is
327 the smallest one */
328 if (ec->model == MPI_EC_WEIERSTRASS)
329 {
330 mpi_free (y);
331 y = negative;
332 }
333 else
334 {
335 mpi_free (x);
336 x = negative;
337 }
338 mpi_sub (ec->d, ec->n, ec->d); /* d = order - d */
339 ec->Q = mpi_point_set (NULL, x, y, mpi_const (MPI_C_ONE));
340
341 if (DBG_CIPHER)
342 log_debug ("ecgen converted Q to a compliant point\n");
343 }
344 else /* p - y >= p */
345 {
346 /* No change is needed exactly 50% of the time: just copy. */
347 mpi_free (negative);
348 ec->Q = mpi_point_set (NULL, Q.x, Q.y, Q.z);
349 if (DBG_CIPHER)
350 log_debug ("ecgen didn't need to convert Q to a compliant point\n");
351 }
352 }
353
354 *r_x = x;
355 if (r_y)
356 *r_y = y;
357
358 point_free (&Q);
359 /* Now we can test our keys (this should never fail!). */
360 if ((flags & PUBKEY_FLAG_NO_KEYTEST))
361 ; /* User requested to skip the test. */
362 else if (ec->model == MPI_EC_MONTGOMERY)
363 test_ecdh_only_keys (ec, ec->nbits - 63, flags);
364 else if (!fips_mode ())
365 test_keys (ec, ec->nbits - 64);
366
367 return 0;
368 }
369
370
371 /*
372 * To verify correct skey it use a random information.
373 * First, encrypt and decrypt this dummy value,
374 * test if the information is recuperated.
375 * Second, test with the sign and verify functions.
376 */
377 static void
378 test_keys (mpi_ec_t ec, unsigned int nbits)
379 {
380 gcry_mpi_t test = mpi_new (nbits);
381 mpi_point_struct R_;
382 gcry_mpi_t c = mpi_new (nbits);
383 gcry_mpi_t out = mpi_new (nbits);
384 gcry_mpi_t r = mpi_new (nbits);
385 gcry_mpi_t s = mpi_new (nbits);
386
387 if (DBG_CIPHER)
388 log_debug ("Testing key.\n");
389
390 point_init (&R_, ec->nbits);
391
392 _gcry_mpi_randomize (test, nbits, GCRY_WEAK_RANDOM);
393
394 if (_gcry_ecc_ecdsa_sign (test, NULL, ec, r, s, 0, 0) )
395 log_fatal ("ECDSA operation: sign failed\n");
396
397 if (_gcry_ecc_ecdsa_verify (test, ec, r, s, 0, 0))
398 {
399 log_fatal ("ECDSA operation: sign, verify failed\n");
400 }
401
402 if (DBG_CIPHER)
403 log_debug ("ECDSA operation: sign, verify ok.\n");
404
405 point_free (&R_);
406 mpi_free (s);
407 mpi_free (r);
408 mpi_free (out);
409 mpi_free (c);
410 mpi_free (test);
411 }
412
413 /* We should get here only with the NIST curves as they are the only ones
414 * having the fips bit set in ecc_domain_parms_t struct so this is slightly
415 * simpler than the whole ecc_generate function */
416 static int
417 test_keys_fips (gcry_sexp_t skey)
418 {
419 int result = -1; /* Default to failure */
420 gcry_md_hd_t hd = NULL;
421 const char *data_tmpl = "(data (flags rfc6979) (hash %s %b))";
422 gcry_sexp_t sig = NULL;
423 char plaintext[128];
424 int rc;
425
426 /* Create a random plaintext. */
427 _gcry_randomize (plaintext, sizeof plaintext, GCRY_WEAK_RANDOM);
428
429 /* Open MD context and feed the random data in */
430 rc = _gcry_md_open (&hd, GCRY_MD_SHA256, 0);
431 if (rc)
432 {
433 log_error ("ECDSA operation: failed to initialize MD context: %s\n", gpg_strerror (rc));
434 goto leave;
435 }
436 _gcry_md_write (hd, plaintext, sizeof(plaintext));
437
438 /* Sign the data */
439 rc = _gcry_pk_sign_md (&sig, data_tmpl, hd, skey, NULL);
440 if (rc)
441 {
442 log_error ("ECDSA operation: signing failed: %s\n", gpg_strerror (rc));
443 goto leave;
444 }
445
446 /* Verify this signature. */
447 rc = _gcry_pk_verify_md (sig, data_tmpl, hd, skey, NULL);
448 if (rc)
449 {
450 log_error ("ECDSA operation: verification failed: %s\n", gpg_strerror (rc));
451 goto leave;
452 }
453
454 /* Modify the data and check that the signing fails. */
455 _gcry_md_reset(hd);
456 plaintext[sizeof plaintext / 2] ^= 1;
457 _gcry_md_write (hd, plaintext, sizeof(plaintext));
458 rc = _gcry_pk_verify_md (sig, data_tmpl, hd, skey, NULL);
459 if (rc != GPG_ERR_BAD_SIGNATURE)
460 {
461 log_error ("ECDSA operation: signature verification worked on modified data\n");
462 goto leave;
463 }
464
465 result = 0;
466 leave:
467 _gcry_md_close (hd);
468 sexp_release (sig);
469 return result;
470 }
471
472 static int
473 test_keys_eddsa_fips (gcry_sexp_t skey)
474 {
475 int result = -1; /* Default to failure */
476 gcry_ctx_t ctx = NULL;
477 const char *data_tmpl = "(data (value %b))";
478 gcry_sexp_t sig = NULL;
479 char plaintext[128];
480 int rc;
481
482 /* Create a random plaintext. */
483 _gcry_randomize (plaintext, sizeof plaintext, GCRY_WEAK_RANDOM);
484
485 rc = _gcry_pk_single_data_push (&ctx, (void *)plaintext, sizeof(plaintext));
486 if (rc)
487 {
488 log_error ("EdDSA operation: failed to push input data: %s\n",
489 gpg_strerror (rc));
490 goto leave;
491 }
492
493 /* Sign the data */
494 rc = _gcry_pk_sign_md (&sig, data_tmpl, NULL, skey, ctx);
495 if (rc)
496 {
497 log_error ("EdDSA operation: signing failed: %s\n", gpg_strerror (rc));
498 goto leave;
499 }
500
501 /* Verify this signature. */
502 rc = _gcry_pk_verify_md (sig, data_tmpl, NULL, skey, ctx);
503 if (rc)
504 {
505 log_error ("EdDSA operation: verification failed: %s\n", gpg_strerror (rc));
506 goto leave;
507 }
508
509 _gcry_ctx_release (ctx);
510 ctx = NULL;
511
512 /* Modify the data and check that the signing fails. */
513 plaintext[sizeof plaintext / 2] ^= 1;
514 rc = _gcry_pk_single_data_push (&ctx, (void *)plaintext, sizeof(plaintext));
515 if (rc)
516 {
517 log_error ("EdDSA operation: failed to push input data: %s\n",
518 gpg_strerror (rc));
519 goto leave;
520 }
521
522 rc = _gcry_pk_verify_md (sig, data_tmpl, NULL, skey, ctx);
523 if (rc != GPG_ERR_BAD_SIGNATURE)
524 {
525 log_error ("EdDSA operation: signature verification worked on modified data\n");
526 goto leave;
527 }
528
529 result = 0;
530 leave:
531 _gcry_ctx_release (ctx);
532 sexp_release (sig);
533 return result;
534 }
535
536
537 static void
538 test_ecdh_only_keys (mpi_ec_t ec, unsigned int nbits, int flags)
539 {
540 gcry_mpi_t test;
541 mpi_point_struct R_;
542 gcry_mpi_t x0, x1;
543
544 if (DBG_CIPHER)
545 log_debug ("Testing ECDH only key.\n");
546
547 point_init (&R_, ec->nbits);
548
549 if (ec->dialect == ECC_DIALECT_SAFECURVE || (flags & PUBKEY_FLAG_DJB_TWEAK))
550 {
551 char *rndbuf;
552 const unsigned int pbits = ec->nbits;
553 int len = (pbits+7)/8;
554
555 rndbuf = _gcry_random_bytes (len, GCRY_WEAK_RANDOM);
556 if (ec->dialect == ECC_DIALECT_SAFECURVE)
557 test = mpi_set_opaque (NULL, rndbuf, len*8);
558 else
559 {
560 test = mpi_new (pbits);
561 if ((pbits % 8))
562 rndbuf[0] &= (1 << (pbits % 8)) - 1;
563 rndbuf[0] |= (1 << ((pbits + 7) % 8));
564 rndbuf[len-1] &= (256 - ec->h);
565 _gcry_mpi_set_buffer (test, rndbuf, len, 0);
566 xfree (rndbuf);
567 }
568 }
569 else
570 {
571 test = mpi_new (nbits);
572 _gcry_mpi_randomize (test, nbits, GCRY_WEAK_RANDOM);
573 }
574
575 x0 = mpi_new (ec->nbits);
576 x1 = mpi_new (ec->nbits);
577
578 /* R_ = hkQ <=> R_ = hkdG */
579 _gcry_mpi_ec_mul_point (&R_, test, ec->Q, ec);
580 if (ec->dialect == ECC_DIALECT_STANDARD && !(flags & PUBKEY_FLAG_DJB_TWEAK))
581 _gcry_mpi_ec_mul_point (&R_, _gcry_mpi_get_const (ec->h), &R_, ec);
582 if (_gcry_mpi_ec_get_affine (x0, NULL, &R_, ec))
583 log_fatal ("ecdh: Failed to get affine coordinates for hkQ\n");
584
585 _gcry_mpi_ec_mul_point (&R_, test, ec->G, ec);
586 _gcry_mpi_ec_mul_point (&R_, ec->d, &R_, ec);
587 /* R_ = hdkG */
588 if (ec->dialect == ECC_DIALECT_STANDARD && !(flags & PUBKEY_FLAG_DJB_TWEAK))
589 _gcry_mpi_ec_mul_point (&R_, _gcry_mpi_get_const (ec->h), &R_, ec);
590
591 if (_gcry_mpi_ec_get_affine (x1, NULL, &R_, ec))
592 log_fatal ("ecdh: Failed to get affine coordinates for hdkG\n");
593
594 if (mpi_cmp (x0, x1))
595 {
596 log_fatal ("ECDH test failed.\n");
597 }
598
599 mpi_free (x0);
600 mpi_free (x1);
601
602 point_free (&R_);
603 mpi_free (test);
604 }
605
606
607 /*
608 * To check the validity of the value, recalculate the correspondence
609 * between the public value and the secret one.
610 */
611 static int
612 check_secret_key (mpi_ec_t ec, int flags)
613 {
614 int rc = 1;
615 mpi_point_struct Q;
616 gcry_mpi_t x1, y1;
617 gcry_mpi_t x2 = NULL;
618 gcry_mpi_t y2 = NULL;
619
620 point_init (&Q, ec->nbits);
621 x1 = mpi_new (ec->nbits);
622 if (ec->model == MPI_EC_MONTGOMERY)
623 y1 = NULL;
624 else
625 y1 = mpi_new (ec->nbits);
626
627 /* G in E(F_p) */
628 if (!_gcry_mpi_ec_curve_point (ec->G, ec))
629 {
630 if (DBG_CIPHER)
631 log_debug ("Bad check: Point 'G' does not belong to curve 'E'!\n");
632 goto leave;
633 }
634
635 /* G != PaI */
636 if (!mpi_cmp_ui (ec->G->z, 0))
637 {
638 if (DBG_CIPHER)
639 log_debug ("Bad check: 'G' cannot be Point at Infinity!\n");
640 goto leave;
641 }
642
643 /* Check order of curve. */
644 if (ec->dialect == ECC_DIALECT_STANDARD && !(flags & PUBKEY_FLAG_DJB_TWEAK))
645 {
646 _gcry_mpi_ec_mul_point (&Q, ec->n, ec->G, ec);
647 if (mpi_cmp_ui (Q.z, 0))
648 {
649 if (DBG_CIPHER)
650 log_debug ("check_secret_key: E is not a curve of order n\n");
651 goto leave;
652 }
653 }
654
655 /* Pubkey cannot be PaI */
656 if (!mpi_cmp_ui (ec->Q->z, 0))
657 {
658 if (DBG_CIPHER)
659 log_debug ("Bad check: Q can not be a Point at Infinity!\n");
660 goto leave;
661 }
662
663 /* pubkey = [d]G over E */
664 if (!_gcry_ecc_compute_public (&Q, ec))
665 {
666 if (DBG_CIPHER)
667 log_debug ("Bad check: computation of dG failed\n");
668 goto leave;
669 }
670 if (_gcry_mpi_ec_get_affine (x1, y1, &Q, ec))
671 {
672 if (DBG_CIPHER)
673 log_debug ("Bad check: Q can not be a Point at Infinity!\n");
674 goto leave;
675 }
676
677 if (!mpi_cmp_ui (ec->Q->z, 1))
678 {
679 /* Fast path if Q is already in affine coordinates. */
680 if (mpi_cmp (x1, ec->Q->x) || (y1 && mpi_cmp (y1, ec->Q->y)))
681 {
682 if (DBG_CIPHER)
683 log_debug
684 ("Bad check: There is NO correspondence between 'd' and 'Q'!\n");
685 goto leave;
686 }
687 }
688 else
689 {
690 x2 = mpi_new (ec->nbits);
691 y2 = mpi_new (ec->nbits);
692 if (_gcry_mpi_ec_get_affine (x2, y2, ec->Q, ec))
693 {
694 if (DBG_CIPHER)
695 log_debug ("Bad check: Q can not be a Point at Infinity!\n");
696 goto leave;
697 }
698
699 if (mpi_cmp (x1, x2) || mpi_cmp (y1, y2))
700 {
701 if (DBG_CIPHER)
702 log_debug
703 ("Bad check: There is NO correspondence between 'd' and 'Q'!\n");
704 goto leave;
705 }
706 }
707 rc = 0; /* Okay. */
708
709 leave:
710 mpi_free (x2);
711 mpi_free (x1);
712 mpi_free (y1);
713 mpi_free (y2);
714 point_free (&Q);
715 return rc;
716 }
717
718
719
720 /*********************************************
721 ************** interface ******************
722 *********************************************/
723
724 static gcry_err_code_t
725 ecc_generate (const gcry_sexp_t genparms, gcry_sexp_t *r_skey)
726 {
727 gpg_err_code_t rc;
728 gcry_mpi_t Gx = NULL;
729 gcry_mpi_t Gy = NULL;
730 gcry_mpi_t Qx = NULL;
731 gcry_mpi_t Qy = NULL;
732 mpi_ec_t ec = NULL;
733 gcry_sexp_t curve_info = NULL;
734 gcry_sexp_t curve_flags = NULL;
735 gcry_mpi_t base = NULL;
736 gcry_mpi_t public = NULL;
737 int flags = GCRYECC_FLAG_LEAST_LEAK;
738
739 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecgen curve", genparms, NULL);
740 if (rc)
741 goto leave;
742
743 if ((flags & PUBKEY_FLAG_EDDSA)
744 || (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE))
745 rc = _gcry_ecc_eddsa_genkey (ec, flags);
746 else if (ec->model == MPI_EC_MONTGOMERY)
747 rc = nist_generate_key (ec, flags, &Qx, NULL);
748 else
749 rc = nist_generate_key (ec, flags, &Qx, &Qy);
750 if (rc)
751 goto leave;
752
753 /* Copy data to the result. */
754 Gx = mpi_new (ec->nbits);
755 Gy = mpi_new (ec->nbits);
756 if (ec->model != MPI_EC_MONTGOMERY)
757 {
758 if (_gcry_mpi_ec_get_affine (Gx, Gy, ec->G, ec))
759 log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "G");
760 base = _gcry_ecc_ec2os (Gx, Gy, ec->p);
761 }
762 if (((ec->dialect == ECC_DIALECT_SAFECURVE && ec->model == MPI_EC_EDWARDS)
763 || ec->dialect == ECC_DIALECT_ED25519 || ec->model == MPI_EC_MONTGOMERY)
764 && !(flags & PUBKEY_FLAG_NOCOMP))
765 {
766 unsigned char *encpk;
767 unsigned int encpklen;
768
769 if (ec->model == MPI_EC_MONTGOMERY)
770 rc = _gcry_ecc_mont_encodepoint (Qx, ec->nbits,
771 ec->dialect != ECC_DIALECT_SAFECURVE,
772 &encpk, &encpklen);
773 else
774 /* (Gx and Gy are used as scratch variables) */
775 rc = _gcry_ecc_eddsa_encodepoint (ec->Q, ec, Gx, Gy,
776 (ec->dialect != ECC_DIALECT_SAFECURVE
777 && !!(flags & PUBKEY_FLAG_COMP)),
778 &encpk, &encpklen);
779 if (rc)
780 goto leave;
781 public = mpi_new (0);
782 mpi_set_opaque (public, encpk, encpklen*8);
783 }
784 else
785 {
786 if (!Qx)
787 {
788 /* This is the case for a key from _gcry_ecc_eddsa_generate
789 with no compression. */
790 Qx = mpi_new (ec->nbits);
791 Qy = mpi_new (ec->nbits);
792 if (_gcry_mpi_ec_get_affine (Qx, Qy, ec->Q, ec))
793 log_fatal ("ecgen: Failed to get affine coordinates for %s\n", "Q");
794 }
795 public = _gcry_ecc_ec2os (Qx, Qy, ec->p);
796 }
797 if (ec->name)
798 {
799 rc = sexp_build (&curve_info, NULL, "(curve %s)", ec->name);
800 if (rc)
801 goto leave;
802 }
803
804 if ((flags & PUBKEY_FLAG_PARAM) || (flags & PUBKEY_FLAG_EDDSA)
805 || (flags & PUBKEY_FLAG_DJB_TWEAK))
806 {
807 rc = sexp_build
808 (&curve_flags, NULL,
809 ((flags & PUBKEY_FLAG_PARAM) && (flags & PUBKEY_FLAG_EDDSA))?
810 "(flags param eddsa)" :
811 ((flags & PUBKEY_FLAG_PARAM) && (flags & PUBKEY_FLAG_DJB_TWEAK))?
812 "(flags param djb-tweak)" :
813 ((flags & PUBKEY_FLAG_PARAM))?
814 "(flags param)" : ((flags & PUBKEY_FLAG_EDDSA))?
815 "(flags eddsa)" : "(flags djb-tweak)" );
816 if (rc)
817 goto leave;
818 }
819
820 if ((flags & PUBKEY_FLAG_PARAM) && ec->name)
821 rc = sexp_build (r_skey, NULL,
822 "(key-data"
823 " (public-key"
824 " (ecc%S%S(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)))"
825 " (private-key"
826 " (ecc%S%S(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)(d%m)))"
827 " )",
828 curve_info, curve_flags,
829 ec->p, ec->a, ec->b, base, ec->n, ec->h, public,
830 curve_info, curve_flags,
831 ec->p, ec->a, ec->b, base, ec->n, ec->h, public,
832 ec->d);
833 else
834 rc = sexp_build (r_skey, NULL,
835 "(key-data"
836 " (public-key"
837 " (ecc%S%S(q%m)))"
838 " (private-key"
839 " (ecc%S%S(q%m)(d%m)))"
840 " )",
841 curve_info, curve_flags,
842 public,
843 curve_info, curve_flags,
844 public, ec->d);
845 if (rc)
846 goto leave;
847
848 if (DBG_CIPHER)
849 {
850 log_printmpi ("ecgen result p", ec->p);
851 log_printmpi ("ecgen result a", ec->a);
852 log_printmpi ("ecgen result b", ec->b);
853 log_printmpi ("ecgen result G", base);
854 log_printmpi ("ecgen result n", ec->n);
855 log_debug ("ecgen result h:+%02x\n", ec->h);
856 log_printmpi ("ecgen result Q", public);
857 log_printmpi ("ecgen result d", ec->d);
858 if ((flags & PUBKEY_FLAG_EDDSA))
859 log_debug ("ecgen result using Ed25519+EdDSA\n");
860 }
861
862 if (fips_mode ())
863 {
864 int result;
865
866 if (ec->model == MPI_EC_EDWARDS)
867 result = test_keys_eddsa_fips (*r_skey);
868 else
869 result = test_keys_fips (*r_skey);
870 if (result)
871 {
872 sexp_release (*r_skey);
873 *r_skey = NULL;
874 fips_signal_error ("self-test after key generation failed");
875 rc = GPG_ERR_SELFTEST_FAILED;
876 }
877 }
878
879 leave:
880 mpi_free (public);
881 mpi_free (base);
882 mpi_free (Gx);
883 mpi_free (Gy);
884 mpi_free (Qx);
885 mpi_free (Qy);
886 _gcry_mpi_ec_free (ec);
887 sexp_release (curve_flags);
888 sexp_release (curve_info);
889 return rc;
890 }
891
892
893 static gcry_err_code_t
894 ecc_check_secret_key (gcry_sexp_t keyparms)
895 {
896 gcry_err_code_t rc;
897 int flags = GCRYECC_FLAG_LEAST_LEAK;
898 mpi_ec_t ec = NULL;
899
900 /*
901 * Extract the key.
902 */
903 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_testkey", keyparms, NULL);
904 if (rc)
905 goto leave;
906 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->Q || !ec->d)
907 {
908 rc = GPG_ERR_NO_OBJ;
909 goto leave;
910 }
911
912 if (check_secret_key (ec, flags))
913 rc = GPG_ERR_BAD_SECKEY;
914
915 leave:
916 _gcry_mpi_ec_free (ec);
917 if (DBG_CIPHER)
918 log_debug ("ecc_testkey => %s\n", gpg_strerror (rc));
919 return rc;
920 }
921
922
923 static gcry_err_code_t
924 ecc_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_data, gcry_sexp_t keyparms)
925 {
926 gcry_err_code_t rc;
927 struct pk_encoding_ctx ctx;
928 gcry_mpi_t data = NULL;
929 gcry_mpi_t k = NULL;
930 gcry_mpi_t sig_r = NULL;
931 gcry_mpi_t sig_s = NULL;
932 mpi_ec_t ec = NULL;
933 int flags = GCRYECC_FLAG_LEAST_LEAK;
934
935 _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, 0);
936
937 /*
938 * Extract the key.
939 */
940 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_sign", keyparms, NULL);
941 if (rc)
942 goto leave;
943 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->d)
944 {
945 rc = GPG_ERR_NO_OBJ;
946 goto leave;
947 }
948
949 ctx.flags |= flags;
950 if (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE)
951 ctx.flags |= PUBKEY_FLAG_EDDSA;
952 /* Clear hash algo for EdDSA. */
953 if ((ctx.flags & PUBKEY_FLAG_EDDSA))
954 ctx.hash_algo = GCRY_MD_NONE;
955
956 /* Extract the data. */
957 rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx);
958 if (rc)
959 goto leave;
960 if (DBG_CIPHER)
961 log_mpidump ("ecc_sign data", data);
962
963 if (ctx.label)
964 {
965 /* ECDSA signing can have supplied K (for testing, deterministic). */
966 if (fips_mode ())
967 {
968 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK_ECC_K))
969 {
970 rc = GPG_ERR_INV_DATA;
971 goto leave;
972 }
973 else
974 fips_service_indicator_mark_non_compliant ();
975 }
976 rc = _gcry_mpi_scan (&k, GCRYMPI_FMT_USG, ctx.label, ctx.labellen, NULL);
977 if (rc)
978 goto leave;
979 }
980
981 if (fips_mode ()
982 && ((ctx.flags & PUBKEY_FLAG_GOST) || (ctx.flags & PUBKEY_FLAG_SM2)))
983 {
984 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK_GOST_SM2))
985 {
986 rc = GPG_ERR_INV_DATA;
987 goto leave;
988 }
989 else
990 fips_service_indicator_mark_non_compliant ();
991 }
992
993 /* Hash algo is determined by curve in EdDSA. */
994 if ((ctx.flags & PUBKEY_FLAG_EDDSA))
995 {
996 if (ctx.hash_algo)
997 {
998 if (fips_mode ()
999 && ((ec->dialect == ECC_DIALECT_ED25519
1000 &&ctx.hash_algo != GCRY_MD_SHA512)
1001 || (ec->dialect == ECC_DIALECT_SAFECURVE
1002 && ctx.hash_algo != GCRY_MD_SHAKE256)))
1003 {
1004 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK))
1005 {
1006 rc = GPG_ERR_DIGEST_ALGO;
1007 goto leave;
1008 }
1009 else
1010 fips_service_indicator_mark_non_compliant ();
1011 }
1012 }
1013 else
1014 {
1015 if (ec->dialect == ECC_DIALECT_ED25519)
1016 ctx.hash_algo = GCRY_MD_SHA512;
1017 else if (ec->dialect == ECC_DIALECT_SAFECURVE)
1018 ctx.hash_algo = GCRY_MD_SHAKE256;
1019 }
1020 }
1021 else
1022 {
1023 if (fips_mode ())
1024 {
1025 if (_gcry_md_algo_info (ctx.hash_algo, GCRYCTL_TEST_ALGO, NULL, NULL)
1026 || ctx.hash_algo == GCRY_MD_SHA1)
1027 {
1028 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK_MD))
1029 {
1030 rc = GPG_ERR_DIGEST_ALGO;
1031 goto leave;
1032 }
1033 else
1034 fips_service_indicator_mark_non_compliant ();
1035 }
1036 }
1037 }
1038
1039 sig_r = mpi_new (0);
1040 sig_s = mpi_new (0);
1041 if ((ctx.flags & PUBKEY_FLAG_EDDSA))
1042 {
1043 /* EdDSA requires the public key. */
1044 rc = _gcry_ecc_eddsa_sign (data, ec, sig_r, sig_s, &ctx);
1045 if (!rc)
1046 rc = sexp_build (r_sig, NULL,
1047 "(sig-val(eddsa(r%M)(s%M)))", sig_r, sig_s);
1048 }
1049 else if ((ctx.flags & PUBKEY_FLAG_GOST))
1050 {
1051 rc = _gcry_ecc_gost_sign (data, ec, sig_r, sig_s);
1052 if (!rc)
1053 rc = sexp_build (r_sig, NULL,
1054 "(sig-val(gost(r%M)(s%M)))", sig_r, sig_s);
1055 }
1056 else if ((ctx.flags & PUBKEY_FLAG_SM2))
1057 {
1058 rc = _gcry_ecc_sm2_sign (data, ec, sig_r, sig_s,
1059 ctx.flags, ctx.hash_algo);
1060 if (!rc)
1061 rc = sexp_build (r_sig, NULL,
1062 "(sig-val(sm2(r%M)(s%M)))", sig_r, sig_s);
1063 }
1064 else
1065 {
1066 rc = _gcry_ecc_ecdsa_sign (data, k, ec, sig_r, sig_s,
1067 ctx.flags, ctx.hash_algo);
1068 if (!rc)
1069 rc = sexp_build (r_sig, NULL,
1070 "(sig-val(ecdsa(r%M)(s%M)))", sig_r, sig_s);
1071 }
1072
1073 leave:
1074 _gcry_mpi_release (sig_r);
1075 _gcry_mpi_release (sig_s);
1076 _gcry_mpi_release (data);
1077 _gcry_mpi_release (k);
1078 _gcry_mpi_ec_free (ec);
1079 _gcry_pk_util_free_encoding_ctx (&ctx);
1080 if (DBG_CIPHER)
1081 log_debug ("ecc_sign => %s\n", gpg_strerror (rc));
1082 return rc;
1083 }
1084
1085
1086 static gcry_err_code_t
1087 ecc_verify (gcry_sexp_t s_sig, gcry_sexp_t s_data, gcry_sexp_t s_keyparms)
1088 {
1089 gcry_err_code_t rc;
1090 struct pk_encoding_ctx ctx;
1091 gcry_sexp_t l1 = NULL;
1092 gcry_mpi_t sig_r = NULL;
1093 gcry_mpi_t sig_s = NULL;
1094 gcry_mpi_t data = NULL;
1095 int sigflags;
1096 mpi_ec_t ec = NULL;
1097 int flags = 0;
1098
1099 _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY,
1100 ecc_get_nbits (s_keyparms));
1101
1102 /*
1103 * Extract the key.
1104 */
1105 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_verify",
1106 s_keyparms, NULL);
1107 if (rc)
1108 goto leave;
1109 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->Q)
1110 {
1111 rc = GPG_ERR_NO_OBJ;
1112 goto leave;
1113 }
1114
1115 if (ec->model == MPI_EC_MONTGOMERY)
1116 {
1117 if (DBG_CIPHER)
1118 log_debug ("ecc_verify: Can't use a Montgomery curve\n");
1119 rc = GPG_ERR_INTERNAL;
1120 goto leave;
1121 }
1122
1123 ctx.flags |= flags;
1124 if (ec->model == MPI_EC_EDWARDS && ec->dialect == ECC_DIALECT_SAFECURVE)
1125 ctx.flags |= PUBKEY_FLAG_EDDSA;
1126 /* Clear hash algo for EdDSA. */
1127 if ((ctx.flags & PUBKEY_FLAG_EDDSA))
1128 ctx.hash_algo = GCRY_MD_NONE;
1129
1130 /* Extract the data. */
1131 rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx);
1132 if (rc)
1133 goto leave;
1134
1135 /*
1136 * ECDSA signing can have supplied K (for testing, deterministic),
1137 * but it's non-compliant. For ECDSA signature verification, having
1138 * K is irrelevant, but an application may use same flags as the one
1139 * for signing.
1140 */
1141 if (ctx.label && fips_mode ())
1142 {
1143 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK_ECC_K))
1144 {
1145 rc = GPG_ERR_INV_DATA;
1146 goto leave;
1147 }
1148 else
1149 fips_service_indicator_mark_non_compliant ();
1150 }
1151
1152 if (DBG_CIPHER)
1153 log_mpidump ("ecc_verify data", data);
1154
1155 if (fips_mode ()
1156 && ((ctx.flags & PUBKEY_FLAG_GOST) || (ctx.flags & PUBKEY_FLAG_SM2)))
1157 {
1158 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK_GOST_SM2))
1159 {
1160 rc = GPG_ERR_INV_DATA;
1161 goto leave;
1162 }
1163 else
1164 fips_service_indicator_mark_non_compliant ();
1165 }
1166
1167 /* Hash algo is determined by curve in EdDSA. */
1168 if ((ctx.flags & PUBKEY_FLAG_EDDSA))
1169 {
1170 if (ctx.hash_algo)
1171 {
1172 if (fips_mode ()
1173 && ((ec->dialect == ECC_DIALECT_ED25519
1174 &&ctx.hash_algo != GCRY_MD_SHA512)
1175 || (ec->dialect == ECC_DIALECT_SAFECURVE
1176 && ctx.hash_algo != GCRY_MD_SHAKE256)))
1177 {
1178 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK))
1179 {
1180 rc = GPG_ERR_DIGEST_ALGO;
1181 goto leave;
1182 }
1183 else
1184 fips_service_indicator_mark_non_compliant ();
1185 }
1186 }
1187 else
1188 {
1189 if (ec->dialect == ECC_DIALECT_ED25519)
1190 ctx.hash_algo = GCRY_MD_SHA512;
1191 else if (ec->dialect == ECC_DIALECT_SAFECURVE)
1192 ctx.hash_algo = GCRY_MD_SHAKE256;
1193 }
1194 }
1195 else
1196 {
1197 if (fips_mode ())
1198 {
1199 if (_gcry_md_algo_info (ctx.hash_algo, GCRYCTL_TEST_ALGO, NULL, NULL)
1200 || ctx.hash_algo == GCRY_MD_SHA1)
1201 {
1202 if (fips_check_rejection (GCRY_FIPS_FLAG_REJECT_PK_MD))
1203 {
1204 rc = GPG_ERR_DIGEST_ALGO;
1205 goto leave;
1206 }
1207 else
1208 fips_service_indicator_mark_non_compliant ();
1209 }
1210 }
1211 }
1212
1213 /*
1214 * Extract the signature value.
1215 */
1216 rc = _gcry_pk_util_preparse_sigval (s_sig, ecc_names, &l1, &sigflags);
1217 if (rc)
1218 goto leave;
1219 rc = sexp_extract_param (l1, NULL, (sigflags & PUBKEY_FLAG_EDDSA)? "/rs":"rs",
1220 &sig_r, &sig_s, NULL);
1221 if (rc)
1222 goto leave;
1223 if (DBG_CIPHER)
1224 {
1225 log_mpidump ("ecc_verify s_r", sig_r);
1226 log_mpidump ("ecc_verify s_s", sig_s);
1227 }
1228 if ((ctx.flags & PUBKEY_FLAG_EDDSA) ^ (sigflags & PUBKEY_FLAG_EDDSA))
1229 {
1230 rc = GPG_ERR_CONFLICT; /* Inconsistent use of flag/algoname. */
1231 goto leave;
1232 }
1233
1234 /*
1235 * Verify the signature.
1236 */
1237 if ((sigflags & PUBKEY_FLAG_EDDSA))
1238 {
1239 rc = _gcry_ecc_eddsa_verify (data, ec, sig_r, sig_s, &ctx);
1240 }
1241 else if ((sigflags & PUBKEY_FLAG_GOST))
1242 {
1243 rc = _gcry_ecc_gost_verify (data, ec, sig_r, sig_s);
1244 }
1245 else if ((sigflags & PUBKEY_FLAG_SM2))
1246 {
1247 rc = _gcry_ecc_sm2_verify (data, ec, sig_r, sig_s);
1248 }
1249 else
1250 {
1251 rc = _gcry_ecc_ecdsa_verify (data, ec, sig_r, sig_s,
1252 ctx.flags, ctx.hash_algo);
1253 }
1254
1255 leave:
1256 _gcry_mpi_release (data);
1257 _gcry_mpi_release (sig_r);
1258 _gcry_mpi_release (sig_s);
1259 _gcry_mpi_ec_free (ec);
1260 sexp_release (l1);
1261 _gcry_pk_util_free_encoding_ctx (&ctx);
1262 if (DBG_CIPHER)
1263 log_debug ("ecc_verify => %s\n", rc?gpg_strerror (rc):"Good");
1264 return rc;
1265 }
1266
1267
1268 /* ecdh raw is classic 2-round DH protocol published in 1976.
1269 *
1270 * Overview of ecc_encrypt_raw and ecc_decrypt_raw.
1271 *
1272 * As with any PK operation, encrypt version uses a public key and
1273 * decrypt -- private.
1274 *
1275 * Symbols used below:
1276 * G - field generator point
1277 * d - private long-term scalar
1278 * dG - public long-term key
1279 * k - ephemeral scalar
1280 * kG - ephemeral public key
1281 * dkG - shared secret
1282 *
1283 * ecc_encrypt_raw description:
1284 * input:
1285 * data[0] : private scalar (k)
1286 * output: A new S-expression with the parameters:
1287 * s : shared point (kdG)
1288 * e : generated ephemeral public key (kG)
1289 *
1290 * ecc_decrypt_raw description:
1291 * input:
1292 * data[0] : a point kG (ephemeral public key)
1293 * output:
1294 * result[0] : shared point (kdG)
1295 */
1296 static gcry_err_code_t
1297 ecc_encrypt_raw (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t keyparms)
1298 {
1299 unsigned int nbits;
1300 gcry_err_code_t rc;
1301 struct pk_encoding_ctx ctx;
1302 gcry_mpi_t mpi_s = NULL;
1303 gcry_mpi_t mpi_e = NULL;
1304 gcry_mpi_t data = NULL;
1305 mpi_ec_t ec = NULL;
1306 int flags = 0;
1307 int no_error_on_infinity;
1308
1309 _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT,
1310 (nbits = ecc_get_nbits (keyparms)));
1311
1312 /*
1313 * Extract the key.
1314 */
1315 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_encrypt", keyparms, NULL);
1316 if (rc)
1317 goto leave;
1318
1319 if (ec->dialect == ECC_DIALECT_SAFECURVE)
1320 {
1321 ctx.flags |= PUBKEY_FLAG_RAW_FLAG;
1322 no_error_on_infinity = 1;
1323 }
1324 else if ((flags & PUBKEY_FLAG_DJB_TWEAK))
1325 no_error_on_infinity = 1;
1326 else
1327 no_error_on_infinity = 0;
1328
1329 /*
1330 * Extract the data.
1331 */
1332 rc = _gcry_pk_util_data_to_mpi (s_data, &data, &ctx);
1333 if (rc)
1334 goto leave;
1335
1336 /*
1337 * Tweak the scalar bits by cofactor and number of bits of the field.
1338 * It assumes the cofactor is a power of 2.
1339 */
1340 if ((flags & PUBKEY_FLAG_DJB_TWEAK))
1341 {
1342 int i;
1343
1344 for (i = 0; (ec->h & (1 << i)) == 0; i++)
1345 mpi_clear_bit (data, i);
1346 mpi_set_highbit (data, ec->nbits - 1);
1347 }
1348 if (DBG_CIPHER)
1349 log_mpidump ("ecc_encrypt data", data);
1350
1351 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->Q)
1352 {
1353 rc = GPG_ERR_NO_OBJ;
1354 goto leave;
1355 }
1356
1357 if ((ctx.flags & PUBKEY_FLAG_SM2))
1358 {
1359 /* All encryption will be done, return it. */
1360 rc = _gcry_ecc_sm2_encrypt (r_ciph, data, ec);
1361 goto leave;
1362 }
1363
1364 /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so */
1365 {
1366 mpi_point_struct R; /* Result that we return. */
1367 gcry_mpi_t x, y;
1368 unsigned char *rawmpi;
1369 unsigned int rawmpilen;
1370
1371 rc = 0;
1372 x = mpi_new (ec->nbits);
1373 if (ec->model == MPI_EC_MONTGOMERY)
1374 y = NULL;
1375 else
1376 y = mpi_new (ec->nbits);
1377
1378 point_init (&R, ec->nbits);
1379
1380 /* R = kQ <=> R = kdG */
1381 _gcry_mpi_ec_mul_point (&R, data, ec->Q, ec);
1382
1383 if (_gcry_mpi_ec_get_affine (x, y, &R, ec))
1384 {
1385 /*
1386 * Here, X is 0. In the X25519 computation on Curve25519, X0
1387 * function maps infinity to zero. So, when PUBKEY_FLAG_DJB_TWEAK
1388 * is enabled, return the result of 0 not raising an error.
1389 *
1390 * This is a corner case. It never occurs with properly
1391 * generated public keys, but it might happen with blindly
1392 * imported public key which might not follow the key
1393 * generation procedure.
1394 */
1395 if (!no_error_on_infinity)
1396 { /* It's not for X25519, then, the input data was simply wrong. */
1397 rc = GPG_ERR_INV_DATA;
1398 goto leave_main;
1399 }
1400 }
1401 if (y)
1402 mpi_s = _gcry_ecc_ec2os (x, y, ec->p);
1403 else
1404 {
1405 rc = _gcry_ecc_mont_encodepoint (x, nbits,
1406 ec->dialect != ECC_DIALECT_SAFECURVE,
1407 &rawmpi, &rawmpilen);
1408 if (rc)
1409 goto leave_main;
1410 mpi_s = mpi_new (0);
1411 mpi_set_opaque (mpi_s, rawmpi, rawmpilen*8);
1412 }
1413
1414 /* R = kG */
1415 _gcry_mpi_ec_mul_point (&R, data, ec->G, ec);
1416
1417 if (_gcry_mpi_ec_get_affine (x, y, &R, ec))
1418 {
1419 rc = GPG_ERR_INV_DATA;
1420 goto leave_main;
1421 }
1422 if (y)
1423 mpi_e = _gcry_ecc_ec2os (x, y, ec->p);
1424 else
1425 {
1426 rc = _gcry_ecc_mont_encodepoint (x, nbits,
1427 ec->dialect != ECC_DIALECT_SAFECURVE,
1428 &rawmpi, &rawmpilen);
1429 if (!rc)
1430 {
1431 mpi_e = mpi_new (0);
1432 mpi_set_opaque (mpi_e, rawmpi, rawmpilen*8);
1433 }
1434 }
1435
1436 leave_main:
1437 mpi_free (x);
1438 mpi_free (y);
1439 point_free (&R);
1440 if (rc)
1441 goto leave;
1442 }
1443
1444 if (!rc)
1445 rc = sexp_build (r_ciph, NULL, "(enc-val(ecdh(s%m)(e%m)))", mpi_s, mpi_e);
1446
1447 leave:
1448 _gcry_mpi_release (data);
1449 _gcry_mpi_release (mpi_s);
1450 _gcry_mpi_release (mpi_e);
1451 _gcry_mpi_ec_free (ec);
1452 _gcry_pk_util_free_encoding_ctx (&ctx);
1453 if (DBG_CIPHER)
1454 log_debug ("ecc_encrypt => %s\n", gpg_strerror (rc));
1455 return rc;
1456 }
1457
1458
1459 /* input:
1460 * data[0] : a point kG (ephemeral public key)
1461 * output:
1462 * resaddr[0] : shared point kdG
1463 *
1464 * see ecc_encrypt_raw for details.
1465 */
1466 static gcry_err_code_t
1467 ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms)
1468 {
1469 unsigned int nbits;
1470 gpg_err_code_t rc;
1471 struct pk_encoding_ctx ctx;
1472 gcry_sexp_t l1 = NULL;
1473 gcry_mpi_t data_e = NULL;
1474 mpi_ec_t ec = NULL;
1475 mpi_point_struct kG;
1476 mpi_point_struct R;
1477 gcry_mpi_t r = NULL;
1478 int flags = GCRYECC_FLAG_LEAST_LEAK;
1479 int enable_specific_point_validation;
1480
1481 nbits = ecc_get_nbits (keyparms);
1482
1483 point_init (&kG, nbits);
1484 point_init (&R, nbits);
1485
1486 _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, nbits);
1487
1488 /*
1489 * Extract the key.
1490 */
1491 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_decrypt", keyparms, NULL);
1492 if (rc)
1493 goto leave;
1494
1495 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n || !ec->d)
1496 {
1497 rc = GPG_ERR_NO_OBJ;
1498 goto leave;
1499 }
1500
1501 /*
1502 * Extract the data.
1503 */
1504 rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx);
1505 if (rc)
1506 goto leave;
1507 if ((ctx.flags & PUBKEY_FLAG_SM2))
1508 {
1509 /* All decryption will be done, return it. */
1510 rc = _gcry_ecc_sm2_decrypt (r_plain, l1, ec);
1511 goto leave;
1512 }
1513 else
1514 {
1515 rc = sexp_extract_param (l1, NULL, "/e", &data_e, NULL);
1516 if (rc)
1517 goto leave;
1518 if (DBG_CIPHER)
1519 log_printmpi ("ecc_decrypt d_e", data_e);
1520 }
1521
1522 if (ec->dialect == ECC_DIALECT_SAFECURVE || (flags & PUBKEY_FLAG_DJB_TWEAK))
1523 enable_specific_point_validation = 1;
1524 else
1525 enable_specific_point_validation = 0;
1526
1527 /*
1528 * Compute the plaintext.
1529 */
1530 if (ec->model == MPI_EC_MONTGOMERY)
1531 rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG);
1532 else
1533 rc = _gcry_ecc_sec_decodepoint (data_e, ec, &kG);
1534 if (rc)
1535 goto leave;
1536
1537 if (DBG_CIPHER)
1538 log_printpnt ("ecc_decrypt kG", &kG, NULL);
1539
1540 if (enable_specific_point_validation)
1541 {
1542 /* For X25519, by its definition, validation should not be done. */
1543 /* (Instead, we do output check.)
1544 *
1545 * However, to mitigate secret key leak from our implementation,
1546 * we also do input validation here. For constant-time
1547 * implementation, we can remove this input validation.
1548 */
1549 if (_gcry_mpi_ec_bad_point (&kG, ec))
1550 {
1551 rc = GPG_ERR_INV_DATA;
1552 goto leave;
1553 }
1554 }
1555 else if (!_gcry_mpi_ec_curve_point (&kG, ec))
1556 {
1557 rc = GPG_ERR_INV_DATA;
1558 goto leave;
1559 }
1560
1561 /* R = dkG */
1562 _gcry_mpi_ec_mul_point (&R, ec->d, &kG, ec);
1563
1564 /* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so: */
1565 {
1566 gcry_mpi_t x, y;
1567
1568 x = mpi_new (ec->nbits);
1569 if (ec->model == MPI_EC_MONTGOMERY)
1570 y = NULL;
1571 else
1572 y = mpi_new (ec->nbits);
1573
1574 if (_gcry_mpi_ec_get_affine (x, y, &R, ec))
1575 {
1576 rc = GPG_ERR_INV_DATA;
1577 goto leave;
1578 /*
1579 * Note for X25519.
1580 *
1581 * By the definition of X25519, this is the case where X25519
1582 * returns 0, mapping infinity to zero. However, we
1583 * deliberately let it return an error.
1584 *
1585 * For X25519 ECDH, comming here means that it might be
1586 * decrypted by anyone with the shared secret of 0 (the result
1587 * of this function could be always 0 by other scalar values,
1588 * other than the private key of D).
1589 *
1590 * So, it looks like an encrypted message but it can be
1591 * decrypted by anyone, or at least something wrong
1592 * happens. Recipient should not proceed as if it were
1593 * properly encrypted message.
1594 *
1595 * This handling is needed for our major usage of GnuPG,
1596 * where it does the One-Pass Diffie-Hellman method,
1597 * C(1, 1, ECC CDH), with an ephemeral key.
1598 */
1599 }
1600
1601 if (y)
1602 r = _gcry_ecc_ec2os (x, y, ec->p);
1603 else
1604 {
1605
1606 unsigned char *rawmpi;
1607 unsigned int rawmpilen;
1608
1609 rc = _gcry_ecc_mont_encodepoint (x, nbits,
1610 ec->dialect != ECC_DIALECT_SAFECURVE,
1611 &rawmpi, &rawmpilen);
1612 if (rc)
1613 goto leave;
1614
1615 r = mpi_new (0);
1616 mpi_set_opaque (r, rawmpi, rawmpilen*8);
1617 }
1618 if (!r)
1619 rc = gpg_err_code_from_syserror ();
1620 else
1621 rc = 0;
1622 mpi_free (x);
1623 mpi_free (y);
1624 }
1625 if (DBG_CIPHER)
1626 log_printmpi ("ecc_decrypt res", r);
1627
1628 if (!rc)
1629 rc = sexp_build (r_plain, NULL, "(value %m)", r);
1630
1631 leave:
1632 point_free (&R);
1633 point_free (&kG);
1634 _gcry_mpi_release (r);
1635 _gcry_mpi_release (data_e);
1636 sexp_release (l1);
1637 _gcry_mpi_ec_free (ec);
1638 _gcry_pk_util_free_encoding_ctx (&ctx);
1639 if (DBG_CIPHER)
1640 log_debug ("ecc_decrypt => %s\n", gpg_strerror (rc));
1641 return rc;
1642 }
1643
1644
1645 /* Return the number of bits for the key described by PARMS. On error
1646 * 0 is returned. The format of PARMS starts with the algorithm name;
1647 * for example:
1648 *
1649 * (ecc
1650 * (curve <name>)
1651 * (p <mpi>)
1652 * (a <mpi>)
1653 * (b <mpi>)
1654 * (g <mpi>)
1655 * (n <mpi>)
1656 * (q <mpi>))
1657 *
1658 * More parameters may be given. Either P or CURVE is needed.
1659 */
1660 static unsigned int
1661 ecc_get_nbits (gcry_sexp_t parms)
1662 {
1663 gcry_sexp_t l1;
1664 gcry_mpi_t p;
1665 unsigned int nbits = 0;
1666 char *curve;
1667
1668 l1 = sexp_find_token (parms, "p", 1);
1669 if (!l1)
1670 { /* Parameter P not found - check whether we have "curve". */
1671 l1 = sexp_find_token (parms, "curve", 5);
1672 if (!l1)
1673 return 0; /* Neither P nor CURVE found. */
1674
1675 curve = sexp_nth_string (l1, 1);
1676 sexp_release (l1);
1677 if (!curve)
1678 return 0; /* No curve name given (or out of core). */
1679
1680 if (_gcry_ecc_fill_in_curve (0, curve, NULL, &nbits))
1681 nbits = 0;
1682 xfree (curve);
1683 }
1684 else
1685 {
1686 p = sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG);
1687 sexp_release (l1);
1688 if (p)
1689 {
1690 nbits = mpi_get_nbits (p);
1691 _gcry_mpi_release (p);
1692 }
1693 }
1694 return nbits;
1695 }
1696
1697
1698 /* See rsa.c for a description of this function. */
1699 static gpg_err_code_t
1700 compute_keygrip (gcry_md_hd_t md, gcry_sexp_t keyparms)
1701 {
1702 #define N_COMPONENTS 6
1703 static const char names[N_COMPONENTS] _GCRY_GCC_ATTR_NONSTRING = "pabgnq";
1704 gpg_err_code_t rc;
1705 gcry_sexp_t l1;
1706 gcry_mpi_t values[N_COMPONENTS];
1707 int idx;
1708 char *curvename = NULL;
1709 int flags = 0;
1710 enum gcry_mpi_ec_models model = 0;
1711 enum ecc_dialects dialect = 0;
1712 const unsigned char *raw;
1713 unsigned int n;
1714 int maybe_uncompress;
1715
1716 /* Clear the values first. */
1717 for (idx=0; idx < N_COMPONENTS; idx++)
1718 values[idx] = NULL;
1719
1720
1721 /* Look for flags. */
1722 l1 = sexp_find_token (keyparms, "flags", 0);
1723 if (l1)
1724 {
1725 rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL);
1726 if (rc)
1727 goto leave;
1728 }
1729
1730 /* Extract the parameters. */
1731 if ((flags & PUBKEY_FLAG_PARAM))
1732 rc = sexp_extract_param (keyparms, NULL, "p?a?b?g?n?/q",
1733 &values[0], &values[1], &values[2],
1734 &values[3], &values[4], &values[5],
1735 NULL);
1736 else
1737 rc = sexp_extract_param (keyparms, NULL, "/q", &values[5], NULL);
1738 if (rc)
1739 goto leave;
1740
1741 /* Check whether a curve parameter is available and use that to fill
1742 in missing values. */
1743 sexp_release (l1);
1744 l1 = sexp_find_token (keyparms, "curve", 5);
1745 if (l1)
1746 {
1747 curvename = sexp_nth_string (l1, 1);
1748 if (curvename)
1749 {
1750 rc = _gcry_ecc_update_curve_param (curvename,
1751 &model, &dialect,
1752 &values[0], &values[1], &values[2],
1753 &values[3], &values[4]);
1754 if (rc)
1755 goto leave;
1756 }
1757 }
1758
1759 /* Guess required fields if a curve parameter has not been given.
1760 FIXME: This is a crude hacks. We need to fix that. */
1761 if (!curvename)
1762 {
1763 model = ((flags & PUBKEY_FLAG_EDDSA)
1764 ? MPI_EC_EDWARDS
1765 : MPI_EC_WEIERSTRASS);
1766 dialect = ((flags & PUBKEY_FLAG_EDDSA)
1767 ? ECC_DIALECT_ED25519
1768 : ECC_DIALECT_STANDARD);
1769 }
1770
1771 /* Check that all parameters are known and normalize all MPIs (that
1772 should not be required but we use an internal function later and
1773 thus we better make 100% sure that they are normalized). */
1774 for (idx = 0; idx < N_COMPONENTS; idx++)
1775 if (!values[idx])
1776 {
1777 rc = GPG_ERR_NO_OBJ;
1778 goto leave;
1779 }
1780 else
1781 _gcry_mpi_normalize (values[idx]);
1782
1783 /* Uncompress the public key with the exception of EdDSA where
1784 compression is the default and we thus compute the keygrip using
1785 the compressed version. Because we don't support any non-eddsa
1786 compression, the only thing we need to do is to compress
1787 EdDSA. */
1788 if ((flags & PUBKEY_FLAG_EDDSA) && dialect == ECC_DIALECT_ED25519)
1789 {
1790 const unsigned int pbits = mpi_get_nbits (values[0]);
1791
1792 rc = _gcry_ecc_eddsa_ensure_compact (values[5], pbits);
1793 if (rc)
1794 goto leave;
1795 maybe_uncompress = 0;
1796 }
1797 else if ((flags & PUBKEY_FLAG_DJB_TWEAK))
1798 {
1799 /* Remove the prefix 0x40 for keygrip computation. */
1800 raw = mpi_get_opaque (values[5], &n);
1801 if (raw)
1802 {
1803 n = (n + 7)/8;
1804
1805 if (n > 1 && (n%2) && raw[0] == 0x40)
1806 if (!_gcry_mpi_set_opaque_copy (values[5], raw + 1, (n - 1)*8))
1807 rc = gpg_err_code_from_syserror ();
1808 }
1809 else
1810 {
1811 rc = GPG_ERR_INV_OBJ;
1812 goto leave;
1813 }
1814 maybe_uncompress = 0;
1815 }
1816 else
1817 maybe_uncompress = 1;
1818
1819 /* Hash them all. */
1820 for (idx = 0; idx < N_COMPONENTS; idx++)
1821 {
1822 char buf[30];
1823 unsigned char *rawbuffer;
1824 unsigned int rawlen;
1825
1826 if (mpi_is_opaque (values[idx]))
1827 {
1828 rawbuffer = NULL;
1829 raw = mpi_get_opaque (values[idx], &rawlen);
1830 rawlen = (rawlen + 7)/8;
1831 }
1832 else
1833 {
1834 rawbuffer = _gcry_mpi_get_buffer (values[idx], 0, &rawlen, NULL);
1835 if (!rawbuffer)
1836 {
1837 rc = gpg_err_code_from_syserror ();
1838 goto leave;
1839 }
1840 raw = rawbuffer;
1841 }
1842
1843 if (maybe_uncompress && idx == 5 && rawlen > 1
1844 && (*raw == 0x02 || *raw == 0x03))
1845 {
1846 /* This is a compressed Q - uncompress. */
1847 mpi_ec_t ec = NULL;
1848 gcry_mpi_t x, y;
1849 gcry_mpi_t x3;
1850 gcry_mpi_t t;
1851 gcry_mpi_t p1_4;
1852 int y_bit = (*raw == 0x03);
1853
1854 /* We need to get the curve parameters as MPIs so that we
1855 * can do computations. We have them in VALUES but it is
1856 * possible that the caller provided them as opaque MPIs. */
1857 rc = _gcry_mpi_ec_internal_new (&ec, &flags, "ecc_keygrip",
1858 keyparms, NULL);
1859 if (rc)
1860 goto leave;
1861 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n)
1862 {
1863 rc = GPG_ERR_NO_OBJ;
1864 _gcry_mpi_ec_free (ec);
1865 goto leave;
1866 }
1867
1868 if (!mpi_test_bit (ec->p, 1))
1869 {
1870 /* No support for point compression for this curve. */
1871 rc = GPG_ERR_NOT_IMPLEMENTED;
1872 _gcry_mpi_ec_free (ec);
1873 xfree (rawbuffer);
1874 goto leave;
1875 }
1876
1877 raw++;
1878 rawlen--;
1879 rc = _gcry_mpi_scan (&x, GCRYMPI_FMT_USG, raw, rawlen, NULL);
1880 if (rc)
1881 {
1882 _gcry_mpi_ec_free (ec);
1883 xfree (rawbuffer);
1884 goto leave;
1885 }
1886
1887 /*
1888 * Recover Y. The Weierstrass curve: y^2 = x^3 + a*x + b
1889 */
1890
1891 x3 = mpi_new (ec->nbits);
1892 t = mpi_new (ec->nbits);
1893 p1_4 = mpi_new (ec->nbits);
1894 y = mpi_new (ec->nbits);
1895
1896 /* Compute right hand side. */
1897 mpi_powm (x3, x, mpi_const (MPI_C_THREE), ec->p);
1898 mpi_mul (t, ec->a, x);
1899 mpi_mod (t, t, ec->p);
1900 mpi_add (t, t, ec->b);
1901 mpi_mod (t, t, ec->p);
1902 mpi_add (t, t, x3);
1903 mpi_mod (t, t, ec->p);
1904
1905 /*
1906 * When p mod 4 = 3, modular square root of A can be computed by
1907 * A^((p+1)/4) mod p
1908 */
1909
1910 /* Compute (p+1)/4 into p1_4 */
1911 mpi_rshift (p1_4, ec->p, 2);
1912 _gcry_mpi_add_ui (p1_4, p1_4, 1);
1913
1914 mpi_powm (y, t, p1_4, ec->p);
1915
1916 if (y_bit != mpi_test_bit (y, 0))
1917 mpi_sub (y, ec->p, y);
1918
1919 mpi_free (p1_4);
1920 mpi_free (t);
1921 mpi_free (x3);
1922
1923 xfree (rawbuffer);
1924 rawbuffer = _gcry_ecc_ec2os_buf (x, y, ec->p, &rawlen);
1925 raw = rawbuffer;
1926
1927 mpi_free (x);
1928 mpi_free (y);
1929 _gcry_mpi_ec_free (ec);
1930 }
1931
1932 snprintf (buf, sizeof buf, "(1:%c%u:", names[idx], rawlen);
1933 _gcry_md_write (md, buf, strlen (buf));
1934 _gcry_md_write (md, raw, rawlen);
1935 _gcry_md_write (md, ")", 1);
1936 xfree (rawbuffer);
1937 }
1938
1939 leave:
1940 xfree (curvename);
1941 sexp_release (l1);
1942 for (idx = 0; idx < N_COMPONENTS; idx++)
1943 _gcry_mpi_release (values[idx]);
1944
1945 return rc;
1946 #undef N_COMPONENTS
1947 }
1948
1949
1950
1951 /*
1952 Low-level API helper functions.
1953 */
1954
1955 /* This is the worker function for gcry_pubkey_get_sexp for ECC
1956 algorithms. Note that the caller has already stored NULL at
1957 R_SEXP. */
1958 gpg_err_code_t
1959 _gcry_pk_ecc_get_sexp (gcry_sexp_t *r_sexp, int mode, mpi_ec_t ec)
1960 {
1961 gpg_err_code_t rc;
1962 gcry_mpi_t mpi_G = NULL;
1963 gcry_mpi_t mpi_Q = NULL;
1964
1965 if (!ec->p || !ec->a || !ec->b || !ec->G || !ec->n)
1966 return GPG_ERR_BAD_CRYPT_CTX;
1967
1968 if (mode == GCRY_PK_GET_SECKEY && !ec->d)
1969 return GPG_ERR_NO_SECKEY;
1970
1971 /* Compute the public point if it is missing. */
1972 if (!ec->Q && ec->d)
1973 ec->Q = _gcry_ecc_compute_public (NULL, ec);
1974
1975 /* Encode G and Q. */
1976 mpi_G = _gcry_mpi_ec_ec2os (ec->G, ec);
1977 if (!mpi_G)
1978 {
1979 rc = GPG_ERR_BROKEN_PUBKEY;
1980 goto leave;
1981 }
1982 if (!ec->Q)
1983 {
1984 rc = GPG_ERR_BAD_CRYPT_CTX;
1985 goto leave;
1986 }
1987
1988 if (ec->dialect == ECC_DIALECT_ED25519)
1989 {
1990 unsigned char *encpk;
1991 unsigned int encpklen;
1992
1993 rc = _gcry_ecc_eddsa_encodepoint (ec->Q, ec, NULL, NULL, 0,
1994 &encpk, &encpklen);
1995 if (rc)
1996 goto leave;
1997 mpi_Q = mpi_set_opaque (NULL, encpk, encpklen*8);
1998 encpk = NULL;
1999 }
2000 else if (ec->model == MPI_EC_MONTGOMERY)
2001 {
2002 unsigned char *encpk;
2003 unsigned int encpklen;
2004
2005 rc = _gcry_ecc_mont_encodepoint (ec->Q->x, ec->nbits,
2006 ec->dialect != ECC_DIALECT_SAFECURVE,
2007 &encpk, &encpklen);
2008 if (rc)
2009 goto leave;
2010 mpi_Q = mpi_set_opaque (NULL, encpk, encpklen*8);
2011 }
2012 else
2013 {
2014 mpi_Q = _gcry_mpi_ec_ec2os (ec->Q, ec);
2015 }
2016 if (!mpi_Q)
2017 {
2018 rc = GPG_ERR_BROKEN_PUBKEY;
2019 goto leave;
2020 }
2021
2022 /* Fixme: We should return a curve name instead of the parameters if
2023 if know that they match a curve. */
2024
2025 if (ec->d && (!mode || mode == GCRY_PK_GET_SECKEY))
2026 {
2027 /* Let's return a private key. */
2028 rc = sexp_build (r_sexp, NULL,
2029 "(private-key(ecc(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)(d%m)))",
2030 ec->p, ec->a, ec->b, mpi_G, ec->n, ec->h, mpi_Q, ec->d);
2031 }
2032 else if (ec->Q)
2033 {
2034 /* Let's return a public key. */
2035 rc = sexp_build (r_sexp, NULL,
2036 "(public-key(ecc(p%m)(a%m)(b%m)(g%m)(n%m)(h%u)(q%m)))",
2037 ec->p, ec->a, ec->b, mpi_G, ec->n, ec->h, mpi_Q);
2038 }
2039 else
2040 rc = GPG_ERR_BAD_CRYPT_CTX;
2041
2042 leave:
2043 mpi_free (mpi_Q);
2044 mpi_free (mpi_G);
2045 return rc;
2046 }
2047
2048
2049
2050 /*
2051 Self-test section.
2052 */
2053
2054 static const char *
2055 selftest_hash_sign (gcry_sexp_t pkey, gcry_sexp_t skey, const char *tmpl,
2056 const char *input_str, const char *input_bad_str,
2057 const char *signature_r, const char *signature_s)
2058 {
2059 int md_algo = GCRY_MD_SHA256;
2060 gcry_md_hd_t hd = NULL;
2061 const char *errtxt = NULL;
2062 gcry_error_t err;
2063 gcry_sexp_t sig = NULL;
2064 gcry_sexp_t l1 = NULL;
2065 gcry_sexp_t l2 = NULL;
2066 gcry_mpi_t r = NULL;
2067 gcry_mpi_t s = NULL;
2068 gcry_mpi_t calculated_r = NULL;
2069 gcry_mpi_t calculated_s = NULL;
2070 int cmp;
2071
2072 err = _gcry_md_open (&hd, md_algo, 0);
2073 if (err)
2074 {
2075 errtxt = "gcry_md_open failed";
2076 goto leave;
2077 }
2078
2079 _gcry_md_write (hd, input_str, strlen (input_str));
2080
2081 err = _gcry_mpi_scan (&r, GCRYMPI_FMT_HEX, signature_r, 0, NULL);
2082 if (!err)
2083 err = _gcry_mpi_scan (&s, GCRYMPI_FMT_HEX, signature_s, 0, NULL);
2084
2085 if (err)
2086 {
2087 errtxt = "converting data failed";
2088 goto leave;
2089 }
2090
2091 err = _gcry_pk_sign_md (&sig, tmpl, hd, skey, NULL);
2092 if (err)
2093 {
2094 errtxt = "signing failed";
2095 goto leave;
2096 }
2097
2098 /* check against known signature */
2099 errtxt = "signature validity failed";
2100 l1 = _gcry_sexp_find_token (sig, "sig-val", 0);
2101 if (!l1)
2102 goto leave;
2103
2104 /* Here, we have the ECC name like: "ecdsa", "eddsa"...,
2105 But we skip parsing the name. */
2106
2107 l2 = _gcry_sexp_find_token (l1, "r", 0);
2108 if (!l2)
2109 goto leave;
2110 calculated_r = _gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
2111 if (!calculated_r)
2112 goto leave;
2113
2114 sexp_release (l2);
2115 l2 = _gcry_sexp_find_token (l1, "s", 0);
2116 if (!l2)
2117 goto leave;
2118 calculated_s = _gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
2119 if (!calculated_s)
2120 goto leave;
2121
2122 errtxt = "known sig check failed";
2123
2124 cmp = _gcry_mpi_cmp (r, calculated_r);
2125 if (cmp)
2126 goto leave;
2127 cmp = _gcry_mpi_cmp (s, calculated_s);
2128 if (cmp)
2129 goto leave;
2130
2131 errtxt = NULL;
2132
2133 /* verify generated signature */
2134 err = _gcry_pk_verify_md (sig, tmpl, hd, pkey, NULL);
2135 if (err)
2136 {
2137 errtxt = "verify failed";
2138 goto leave;
2139 }
2140
2141 _gcry_md_reset(hd);
2142 _gcry_md_write (hd, input_bad_str, strlen (input_bad_str));
2143 err = _gcry_pk_verify_md (sig, tmpl, hd, pkey, NULL);
2144 if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE)
2145 {
2146 errtxt = "bad signature not detected";
2147 goto leave;
2148 }
2149
2150
2151 leave:
2152 _gcry_md_close (hd);
2153 sexp_release (sig);
2154 sexp_release (l1);
2155 sexp_release (l2);
2156 mpi_release (r);
2157 mpi_release (s);
2158 mpi_release (calculated_r);
2159 mpi_release (calculated_s);
2160 return errtxt;
2161 }
2162
2163
2164 static const char *
2165 selftest_hash_sign_eddsa (gcry_sexp_t pkey, gcry_sexp_t skey, const char *tmpl,
2166 const char *input_str, const char *input_bad_str,
2167 const char *signature_r, const char *signature_s)
2168 {
2169 gcry_ctx_t ctx = NULL;
2170 const char *errtxt = NULL;
2171 gcry_error_t err;
2172 gcry_sexp_t sig = NULL;
2173 gcry_sexp_t l1 = NULL;
2174 gcry_sexp_t l2 = NULL;
2175 unsigned char *r = NULL;
2176 unsigned char *s = NULL;
2177 size_t r_len, s_len;
2178 unsigned char *calculated_r = NULL;
2179 unsigned char *calculated_s = NULL;
2180 size_t calculated_r_len, calculated_s_len;
2181
2182 err = _gcry_pk_single_data_push (&ctx, (void *)input_str, strlen (input_str));
2183 if (err)
2184 {
2185 errtxt ="error setting input data";
2186 goto leave;
2187 }
2188
2189 r = _gcry_hex2buffer (signature_r, &r_len);
2190 s = _gcry_hex2buffer (signature_s, &s_len);
2191 if (!r || !s)
2192 {
2193 errtxt = "converting data failed";
2194 goto leave;
2195 }
2196
2197 err = _gcry_pk_sign_md (&sig, tmpl, NULL, skey, ctx);
2198 if (err)
2199 {
2200 errtxt = "signing failed";
2201 goto leave;
2202 }
2203
2204 /* check against known signature */
2205 errtxt = "signature validity failed";
2206 l1 = _gcry_sexp_find_token (sig, "sig-val", 0);
2207 if (!l1)
2208 goto leave;
2209
2210 /* Here, we have the ECC name like: "ecdsa", "eddsa"...,
2211 But we skip parsing the name. */
2212
2213 l2 = _gcry_sexp_find_token (l1, "r", 0);
2214 if (!l2)
2215 goto leave;
2216 calculated_r = _gcry_sexp_nth_buffer (l2, 1, &calculated_r_len);
2217 if (!calculated_r)
2218 goto leave;
2219
2220 sexp_release (l2);
2221 l2 = _gcry_sexp_find_token (l1, "s", 0);
2222 if (!l2)
2223 goto leave;
2224 calculated_s = _gcry_sexp_nth_buffer (l2, 1, &calculated_s_len);
2225 if (!calculated_s)
2226 goto leave;
2227
2228 errtxt = "known sig check failed";
2229
2230 if (r_len != calculated_r_len)
2231 goto leave;
2232 if (s_len != calculated_s_len)
2233 goto leave;
2234 if (memcmp (r, calculated_r, r_len))
2235 goto leave;
2236 if (memcmp (s, calculated_s, s_len))
2237 goto leave;
2238
2239 errtxt = NULL;
2240
2241 /* verify generated signature */
2242 err = _gcry_pk_verify_md (sig, tmpl, NULL, pkey, ctx);
2243 if (err)
2244 {
2245 errtxt = "verify failed";
2246 goto leave;
2247 }
2248
2249 _gcry_ctx_release (ctx);
2250 ctx = NULL;
2251 err = _gcry_pk_single_data_push (&ctx, (void *)input_bad_str,
2252 strlen (input_bad_str));
2253 if (err)
2254 {
2255 errtxt ="error setting input data";
2256 goto leave;
2257 }
2258
2259 err = _gcry_pk_verify_md (sig, tmpl, NULL, pkey, ctx);
2260 if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE)
2261 {
2262 errtxt = "bad signature not detected";
2263 goto leave;
2264 }
2265
2266 leave:
2267 _gcry_ctx_release (ctx);
2268 sexp_release (sig);
2269 sexp_release (l1);
2270 sexp_release (l2);
2271 xfree (r);
2272 xfree (s);
2273 xfree (calculated_r);
2274 xfree (calculated_s);
2275 return errtxt;
2276 }
2277
2278
2279 static const char *
2280 selftest_sign (gcry_sexp_t pkey, gcry_sexp_t skey,
2281 const char *input, const char *input_bad,
2282 const char *signature_r, const char *signature_s)
2283 {
2284 const char *errtxt = NULL;
2285 gcry_error_t err;
2286 gcry_sexp_t data = NULL;
2287 gcry_sexp_t data_bad = NULL;
2288 gcry_sexp_t sig = NULL;
2289 gcry_sexp_t l1 = NULL;
2290 gcry_sexp_t l2 = NULL;
2291 gcry_mpi_t r = NULL;
2292 gcry_mpi_t s = NULL;
2293 gcry_mpi_t calculated_r = NULL;
2294 gcry_mpi_t calculated_s = NULL;
2295 int cmp;
2296
2297 err = sexp_sscan (&data, NULL, input, strlen (input));
2298 if (!err)
2299 err = sexp_sscan (&data_bad, NULL,
2300 input_bad, strlen (input_bad));
2301 if (!err)
2302 err = _gcry_mpi_scan (&r, GCRYMPI_FMT_HEX, signature_r, 0, NULL);
2303 if (!err)
2304 err = _gcry_mpi_scan (&s, GCRYMPI_FMT_HEX, signature_s, 0, NULL);
2305
2306 if (err)
2307 {
2308 errtxt = "converting data failed";
2309 goto leave;
2310 }
2311
2312 err = _gcry_pk_sign (&sig, data, skey);
2313 if (err)
2314 {
2315 errtxt = "signing failed";
2316 goto leave;
2317 }
2318
2319 /* check against known signature */
2320 errtxt = "signature validity failed";
2321 l1 = _gcry_sexp_find_token (sig, "sig-val", 0);
2322 if (!l1)
2323 goto leave;
2324
2325 /* Here, we have the ECC name like: "ecdsa", "eddsa"...,
2326 But we skip parsing the name. */
2327
2328 l2 = _gcry_sexp_find_token (l1, "r", 0);
2329 if (!l2)
2330 goto leave;
2331 calculated_r = _gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
2332 if (!calculated_r)
2333 goto leave;
2334
2335 sexp_release (l2);
2336 l2 = _gcry_sexp_find_token (l1, "s", 0);
2337 if (!l2)
2338 goto leave;
2339 calculated_s = _gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
2340 if (!calculated_s)
2341 goto leave;
2342
2343 errtxt = "known sig check failed";
2344
2345 cmp = _gcry_mpi_cmp (r, calculated_r);
2346 if (cmp)
2347 goto leave;
2348 cmp = _gcry_mpi_cmp (s, calculated_s);
2349 if (cmp)
2350 goto leave;
2351
2352 errtxt = NULL;
2353
2354 /* verify generated signature */
2355 err = _gcry_pk_verify (sig, data, pkey);
2356 if (err)
2357 {
2358 errtxt = "verify failed";
2359 goto leave;
2360 }
2361 err = _gcry_pk_verify (sig, data_bad, pkey);
2362 if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE)
2363 {
2364 errtxt = "bad signature not detected";
2365 goto leave;
2366 }
2367
2368
2369 leave:
2370 sexp_release (sig);
2371 sexp_release (data_bad);
2372 sexp_release (data);
2373 sexp_release (l1);
2374 sexp_release (l2);
2375 mpi_release (r);
2376 mpi_release (s);
2377 mpi_release (calculated_r);
2378 mpi_release (calculated_s);
2379 return errtxt;
2380 }
2381
2382
2383 static gpg_err_code_t
2384 selftests_ecc (selftest_report_func_t report, int extended, int is_eddsa,
2385 const char *secret_key, const char *public_key,
2386 const char *input, const char *input_bad,
2387 const char *tmpl,
2388 const char *input_str, const char *input_bad_str,
2389 const char *signature_r, const char *signature_s)
2390 {
2391 const char *what;
2392 const char *errtxt;
2393 gcry_error_t err;
2394 gcry_sexp_t skey = NULL;
2395 gcry_sexp_t pkey = NULL;
2396
2397 what = "convert";
2398 err = sexp_sscan (&skey, NULL, secret_key, strlen (secret_key));
2399 if (!err)
2400 err = sexp_sscan (&pkey, NULL, public_key, strlen (public_key));
2401 if (err)
2402 {
2403 errtxt = _gcry_strerror (err);
2404 goto failed;
2405 }
2406
2407 what = "key consistency";
2408 err = ecc_check_secret_key (skey);
2409 if (err)
2410 {
2411 errtxt = _gcry_strerror (err);
2412 goto failed;
2413 }
2414
2415 if (extended)
2416 {
2417 what = "sign";
2418 errtxt = selftest_sign (pkey, skey, input, input_bad,
2419 signature_r, signature_s);
2420 if (errtxt)
2421 goto failed;
2422 }
2423
2424 what = "digest sign";
2425 if (is_eddsa)
2426 errtxt = selftest_hash_sign_eddsa (pkey, skey, tmpl,
2427 input_str, input_bad_str,
2428 signature_r, signature_s);
2429 else
2430 errtxt = selftest_hash_sign (pkey, skey, tmpl,
2431 input_str, input_bad_str,
2432 signature_r, signature_s);
2433 if (errtxt)
2434 goto failed;
2435
2436 sexp_release(pkey);
2437 sexp_release(skey);
2438 return 0; /* Succeeded. */
2439
2440 failed:
2441 sexp_release(pkey);
2442 sexp_release(skey);
2443 if (report)
2444 report ("pubkey", GCRY_PK_ECC, what, errtxt);
2445 return GPG_ERR_SELFTEST_FAILED;
2446 }
2447
2448
2449 /* Run a full self-test for ALGO and return 0 on success. */
2450 static gpg_err_code_t
2451 run_selftests (int algo, int extended, selftest_report_func_t report)
2452 {
2453 int r;
2454
2455 if (algo != GCRY_PK_ECC)
2456 return GPG_ERR_PUBKEY_ALGO;
2457
2458 r = selftests_ecc (report, extended, 0,
2459 ecdsa_sample_secret_key_secp256,
2460 ecdsa_sample_public_key_secp256,
2461 ecdsa_sample_data, ecdsa_sample_data_bad,
2462 ecdsa_data_tmpl,
2463 ecdsa_sample_data_string, ecdsa_sample_data_bad_string,
2464 ecdsa_signature_r, ecdsa_signature_s);
2465 if (r)
2466 return r;
2467
2468 r = selftests_ecc (report, extended, 0,
2469 ecdsa_sample_secret_key_secp256,
2470 ecdsa_sample_public_key_secp256,
2471 rfc6979_ecdsa_sample_data, rfc6979_ecdsa_sample_data_bad,
2472 rfc6979_ecdsa_data_tmpl,
2473 ecdsa_sample_data_string, ecdsa_sample_data_bad_string,
2474 ecdsa_signature_r, ecdsa_signature_s);
2475 if (r)
2476 return r;
2477
2478 r = selftests_ecc (report, extended, 1,
2479 ed25519_sample_secret_key,
2480 ed25519_sample_public_key,
2481 ed25519_sample_data, ed25519_sample_data_bad,
2482 ed25519_data_tmpl,
2483 ed25519_sample_data_string, ed25519_sample_data_bad_string,
2484 ed25519_signature_r, ed25519_signature_s);
2485 if (r)
2486 return r;
2487
2488 r = selftests_ecc (report, extended, 1,
2489 ed448_sample_secret_key,
2490 ed448_sample_public_key,
2491 ed448_sample_data, ed448_sample_data_bad,
2492 ed448_data_tmpl,
2493 ed448_sample_data_string, ed448_sample_data_bad_string,
2494 ed448_signature_r, ed448_signature_s);
2495 return r;
2496 }
2497
2498 gcry_pk_spec_t _gcry_pubkey_spec_ecc =
2499 {
2500 GCRY_PK_ECC, { 0, 1 },
2501 (GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR),
2502 "ECC", ecc_names,
2503 "pabgnhq", "pabgnhqd", "se", "rs", "pabgnhq",
2504 ecc_generate,
2505 ecc_check_secret_key,
2506 ecc_encrypt_raw,
2507 ecc_decrypt_raw,
2508 ecc_sign,
2509 ecc_verify,
2510 ecc_get_nbits,
2511 run_selftests,
2512 compute_keygrip,
2513 _gcry_ecc_get_curve,
2514 _gcry_ecc_get_param_sexp
2515 };