Fix migration guide mappings for i2o/o2i_ECPublicKey
[openssl.git] / apps / ecparam.c
1 /*
2  * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include <openssl/opensslconf.h>
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <time.h>
16 #include <string.h>
17 #include "apps.h"
18 #include "progs.h"
19 #include <openssl/bio.h>
20 #include <openssl/err.h>
21 #include <openssl/bn.h>
22 #include <openssl/ec.h>
23 #include <openssl/x509.h>
24 #include <openssl/pem.h>
25
26 typedef enum OPTION_choice {
27     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
28     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_C,
29     OPT_CHECK, OPT_LIST_CURVES, OPT_NO_SEED, OPT_NOOUT, OPT_NAME,
30     OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_ENGINE, OPT_CHECK_NAMED,
31     OPT_R_ENUM, OPT_PROV_ENUM
32 } OPTION_CHOICE;
33
34 const OPTIONS ecparam_options[] = {
35     OPT_SECTION("General"),
36     {"help", OPT_HELP, '-', "Display this summary"},
37     {"list_curves", OPT_LIST_CURVES, '-',
38      "Prints a list of all curve 'short names'"},
39 #ifndef OPENSSL_NO_ENGINE
40     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
41 #endif
42
43     {"genkey", OPT_GENKEY, '-', "Generate ec key"},
44     {"in", OPT_IN, '<', "Input file  - default stdin"},
45     {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"},
46     {"out", OPT_OUT, '>', "Output file - default stdout"},
47     {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"},
48
49     OPT_SECTION("Output"),
50     {"text", OPT_TEXT, '-', "Print the ec parameters in text form"},
51     {"C", OPT_C, '-', "Print a 'C' function creating the parameters"},
52     {"noout", OPT_NOOUT, '-', "Do not print the ec parameter"},
53     {"param_enc", OPT_PARAM_ENC, 's',
54      "Specifies the way the ec parameters are encoded"},
55
56     OPT_SECTION("Parameter"),
57     {"check", OPT_CHECK, '-', "Validate the ec parameters"},
58     {"check_named", OPT_CHECK_NAMED, '-',
59      "Check that named EC curve parameters have not been modified"},
60     {"no_seed", OPT_NO_SEED, '-',
61      "If 'explicit' parameters are chosen do not use the seed"},
62     {"name", OPT_NAME, 's',
63      "Use the ec parameters with specified 'short name'"},
64     {"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "},
65
66     OPT_R_OPTIONS,
67     OPT_PROV_OPTIONS,
68     {NULL}
69 };
70
71 static OPT_PAIR forms[] = {
72     {"compressed", POINT_CONVERSION_COMPRESSED},
73     {"uncompressed", POINT_CONVERSION_UNCOMPRESSED},
74     {"hybrid", POINT_CONVERSION_HYBRID},
75     {NULL}
76 };
77
78 static OPT_PAIR encodings[] = {
79     {"named_curve", OPENSSL_EC_NAMED_CURVE},
80     {"explicit", 0},
81     {NULL}
82 };
83
84 int ecparam_main(int argc, char **argv)
85 {
86     ENGINE *e = NULL;
87     BIGNUM *ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL;
88     BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL;
89     BIO *in = NULL, *out = NULL;
90     EC_GROUP *group = NULL;
91     point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
92     char *curve_name = NULL;
93     char *infile = NULL, *outfile = NULL, *prog;
94     unsigned char *buffer = NULL;
95     OPTION_CHOICE o;
96     int asn1_flag = OPENSSL_EC_NAMED_CURVE, new_asn1_flag = 0;
97     int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0;
98     int ret = 1, private = 0;
99     int list_curves = 0, no_seed = 0, check = 0, new_form = 0;
100     int text = 0, i, genkey = 0, check_named = 0;
101
102     prog = opt_init(argc, argv, ecparam_options);
103     while ((o = opt_next()) != OPT_EOF) {
104         switch (o) {
105         case OPT_EOF:
106         case OPT_ERR:
107  opthelp:
108             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
109             goto end;
110         case OPT_HELP:
111             opt_help(ecparam_options);
112             ret = 0;
113             goto end;
114         case OPT_INFORM:
115             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
116                 goto opthelp;
117             break;
118         case OPT_IN:
119             infile = opt_arg();
120             break;
121         case OPT_OUTFORM:
122             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
123                 goto opthelp;
124             break;
125         case OPT_OUT:
126             outfile = opt_arg();
127             break;
128         case OPT_TEXT:
129             text = 1;
130             break;
131         case OPT_C:
132             C = 1;
133             break;
134         case OPT_CHECK:
135             check = 1;
136             break;
137         case OPT_CHECK_NAMED:
138             check_named = 1;
139             break;
140         case OPT_LIST_CURVES:
141             list_curves = 1;
142             break;
143         case OPT_NO_SEED:
144             no_seed = 1;
145             break;
146         case OPT_NOOUT:
147             noout = 1;
148             break;
149         case OPT_NAME:
150             curve_name = opt_arg();
151             break;
152         case OPT_CONV_FORM:
153             if (!opt_pair(opt_arg(), forms, &new_form))
154                 goto opthelp;
155             form = new_form;
156             new_form = 1;
157             break;
158         case OPT_PARAM_ENC:
159             if (!opt_pair(opt_arg(), encodings, &asn1_flag))
160                 goto opthelp;
161             new_asn1_flag = 1;
162             break;
163         case OPT_GENKEY:
164             genkey = 1;
165             break;
166         case OPT_R_CASES:
167             if (!opt_rand(o))
168                 goto end;
169             break;
170         case OPT_PROV_CASES:
171             if (!opt_provider(o))
172                 goto end;
173             break;
174         case OPT_ENGINE:
175             e = setup_engine(opt_arg(), 0);
176             break;
177         }
178     }
179     argc = opt_num_rest();
180     if (argc != 0)
181         goto opthelp;
182
183     private = genkey ? 1 : 0;
184
185     in = bio_open_default(infile, 'r', informat);
186     if (in == NULL)
187         goto end;
188     out = bio_open_owner(outfile, outformat, private);
189     if (out == NULL)
190         goto end;
191
192     if (list_curves) {
193         EC_builtin_curve *curves = NULL;
194         size_t crv_len = EC_get_builtin_curves(NULL, 0);
195         size_t n;
196
197         curves = app_malloc((int)sizeof(*curves) * crv_len, "list curves");
198         if (!EC_get_builtin_curves(curves, crv_len)) {
199             OPENSSL_free(curves);
200             goto end;
201         }
202
203         for (n = 0; n < crv_len; n++) {
204             const char *comment;
205             const char *sname;
206             comment = curves[n].comment;
207             sname = OBJ_nid2sn(curves[n].nid);
208             if (comment == NULL)
209                 comment = "CURVE DESCRIPTION NOT AVAILABLE";
210             if (sname == NULL)
211                 sname = "";
212
213             BIO_printf(out, "  %-10s: ", sname);
214             BIO_printf(out, "%s\n", comment);
215         }
216
217         OPENSSL_free(curves);
218         ret = 0;
219         goto end;
220     }
221
222     if (curve_name != NULL) {
223         int nid;
224
225         /*
226          * workaround for the SECG curve names secp192r1 and secp256r1 (which
227          * are the same as the curves prime192v1 and prime256v1 defined in
228          * X9.62)
229          */
230         if (strcmp(curve_name, "secp192r1") == 0) {
231             BIO_printf(bio_err, "using curve name prime192v1 "
232                        "instead of secp192r1\n");
233             nid = NID_X9_62_prime192v1;
234         } else if (strcmp(curve_name, "secp256r1") == 0) {
235             BIO_printf(bio_err, "using curve name prime256v1 "
236                        "instead of secp256r1\n");
237             nid = NID_X9_62_prime256v1;
238         } else {
239             nid = OBJ_sn2nid(curve_name);
240         }
241
242         if (nid == 0)
243             nid = EC_curve_nist2nid(curve_name);
244
245         if (nid == 0) {
246             BIO_printf(bio_err, "unknown curve name (%s)\n", curve_name);
247             goto end;
248         }
249
250         group = EC_GROUP_new_by_curve_name(nid);
251         if (group == NULL) {
252             BIO_printf(bio_err, "unable to create curve (%s)\n", curve_name);
253             goto end;
254         }
255         EC_GROUP_set_asn1_flag(group, asn1_flag);
256         EC_GROUP_set_point_conversion_form(group, form);
257     } else if (informat == FORMAT_ASN1) {
258         group = d2i_ECPKParameters_bio(in, NULL);
259     } else {
260         group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL);
261     }
262     if (group == NULL) {
263         BIO_printf(bio_err, "unable to load elliptic curve parameters\n");
264         ERR_print_errors(bio_err);
265         goto end;
266     }
267
268     if (new_form)
269         EC_GROUP_set_point_conversion_form(group, form);
270
271     if (new_asn1_flag)
272         EC_GROUP_set_asn1_flag(group, asn1_flag);
273
274     if (no_seed) {
275         EC_GROUP_set_seed(group, NULL, 0);
276     }
277
278     if (text) {
279         if (!ECPKParameters_print(out, group, 0))
280             goto end;
281     }
282
283     if (check_named) {
284         BIO_printf(bio_err, "validating named elliptic curve parameters: ");
285         if (EC_GROUP_check_named_curve(group, 0, NULL) <= 0) {
286             BIO_printf(bio_err, "failed\n");
287             ERR_print_errors(bio_err);
288             goto end;
289         }
290         BIO_printf(bio_err, "ok\n");
291     }
292
293     if (check) {
294         BIO_printf(bio_err, "checking elliptic curve parameters: ");
295         if (!EC_GROUP_check(group, NULL)) {
296             BIO_printf(bio_err, "failed\n");
297             ERR_print_errors(bio_err);
298             goto end;
299         }
300         BIO_printf(bio_err, "ok\n");
301
302     }
303
304     if (C) {
305         size_t buf_len = 0, tmp_len = 0;
306         const EC_POINT *point;
307         int is_prime, len = 0;
308
309         if ((ec_p = BN_new()) == NULL
310                 || (ec_a = BN_new()) == NULL
311                 || (ec_b = BN_new()) == NULL
312                 || (ec_gen = BN_new()) == NULL
313                 || (ec_order = BN_new()) == NULL
314                 || (ec_cofactor = BN_new()) == NULL) {
315             perror("Can't allocate BN");
316             goto end;
317         }
318
319         is_prime = (EC_GROUP_get_field_type(group) == NID_X9_62_prime_field);
320         if (!is_prime) {
321             BIO_printf(bio_err, "Can only handle X9.62 prime fields\n");
322             goto end;
323         }
324
325         if (!EC_GROUP_get_curve(group, ec_p, ec_a, ec_b, NULL))
326             goto end;
327
328         if ((point = EC_GROUP_get0_generator(group)) == NULL)
329             goto end;
330         if (!EC_POINT_point2bn(group, point,
331                                EC_GROUP_get_point_conversion_form(group),
332                                ec_gen, NULL))
333             goto end;
334         if (!EC_GROUP_get_order(group, ec_order, NULL))
335             goto end;
336         if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL))
337             goto end;
338
339         if (!ec_p || !ec_a || !ec_b || !ec_gen || !ec_order || !ec_cofactor)
340             goto end;
341
342         len = BN_num_bits(ec_order);
343
344         if ((tmp_len = (size_t)BN_num_bytes(ec_p)) > buf_len)
345             buf_len = tmp_len;
346         if ((tmp_len = (size_t)BN_num_bytes(ec_a)) > buf_len)
347             buf_len = tmp_len;
348         if ((tmp_len = (size_t)BN_num_bytes(ec_b)) > buf_len)
349             buf_len = tmp_len;
350         if ((tmp_len = (size_t)BN_num_bytes(ec_gen)) > buf_len)
351             buf_len = tmp_len;
352         if ((tmp_len = (size_t)BN_num_bytes(ec_order)) > buf_len)
353             buf_len = tmp_len;
354         if ((tmp_len = (size_t)BN_num_bytes(ec_cofactor)) > buf_len)
355             buf_len = tmp_len;
356
357         buffer = app_malloc(buf_len, "BN buffer");
358
359         BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n{\n", len);
360         print_bignum_var(out, ec_p, "ec_p", len, buffer);
361         print_bignum_var(out, ec_a, "ec_a", len, buffer);
362         print_bignum_var(out, ec_b, "ec_b", len, buffer);
363         print_bignum_var(out, ec_gen, "ec_gen", len, buffer);
364         print_bignum_var(out, ec_order, "ec_order", len, buffer);
365         print_bignum_var(out, ec_cofactor, "ec_cofactor", len, buffer);
366         BIO_printf(out, "    int ok = 0;\n"
367                         "    EC_GROUP *group = NULL;\n"
368                         "    EC_POINT *point = NULL;\n"
369                         "    BIGNUM *tmp_1 = NULL;\n"
370                         "    BIGNUM *tmp_2 = NULL;\n"
371                         "    BIGNUM *tmp_3 = NULL;\n"
372                         "\n");
373
374         BIO_printf(out, "    if ((tmp_1 = BN_bin2bn(ec_p_%d, sizeof(ec_p_%d), NULL)) == NULL)\n"
375                         "        goto err;\n", len, len);
376         BIO_printf(out, "    if ((tmp_2 = BN_bin2bn(ec_a_%d, sizeof(ec_a_%d), NULL)) == NULL)\n"
377                         "        goto err;\n", len, len);
378         BIO_printf(out, "    if ((tmp_3 = BN_bin2bn(ec_b_%d, sizeof(ec_b_%d), NULL)) == NULL)\n"
379                         "        goto err;\n", len, len);
380         BIO_printf(out, "    if ((group = EC_GROUP_new_curve_GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)\n"
381                         "        goto err;\n"
382                         "\n");
383         BIO_printf(out, "    /* build generator */\n");
384         BIO_printf(out, "    if ((tmp_1 = BN_bin2bn(ec_gen_%d, sizeof(ec_gen_%d), tmp_1)) == NULL)\n"
385                         "        goto err;\n", len, len);
386         BIO_printf(out, "    point = EC_POINT_bn2point(group, tmp_1, NULL, NULL);\n");
387         BIO_printf(out, "    if (point == NULL)\n"
388                         "        goto err;\n");
389         BIO_printf(out, "    if ((tmp_2 = BN_bin2bn(ec_order_%d, sizeof(ec_order_%d), tmp_2)) == NULL)\n"
390                         "        goto err;\n", len, len);
391         BIO_printf(out, "    if ((tmp_3 = BN_bin2bn(ec_cofactor_%d, sizeof(ec_cofactor_%d), tmp_3)) == NULL)\n"
392                         "        goto err;\n", len, len);
393         BIO_printf(out, "    if (!EC_GROUP_set_generator(group, point, tmp_2, tmp_3))\n"
394                         "        goto err;\n"
395                         "ok = 1;"
396                         "\n");
397         BIO_printf(out, "err:\n"
398                         "    BN_free(tmp_1);\n"
399                         "    BN_free(tmp_2);\n"
400                         "    BN_free(tmp_3);\n"
401                         "    EC_POINT_free(point);\n"
402                         "    if (!ok) {\n"
403                         "        EC_GROUP_free(group);\n"
404                         "        return NULL;\n"
405                         "    }\n"
406                         "    return (group);\n"
407                         "}\n");
408     }
409
410     if (outformat == FORMAT_ASN1 && genkey)
411         noout = 1;
412
413     if (!noout) {
414         if (outformat == FORMAT_ASN1)
415             i = i2d_ECPKParameters_bio(out, group);
416         else
417             i = PEM_write_bio_ECPKParameters(out, group);
418         if (!i) {
419             BIO_printf(bio_err, "unable to write elliptic "
420                        "curve parameters\n");
421             ERR_print_errors(bio_err);
422             goto end;
423         }
424     }
425
426     if (genkey) {
427         EC_KEY *eckey = EC_KEY_new();
428
429         if (eckey == NULL)
430             goto end;
431
432         if (EC_KEY_set_group(eckey, group) == 0) {
433             BIO_printf(bio_err, "unable to set group when generating key\n");
434             EC_KEY_free(eckey);
435             ERR_print_errors(bio_err);
436             goto end;
437         }
438
439         if (new_form)
440             EC_KEY_set_conv_form(eckey, form);
441
442         if (!EC_KEY_generate_key(eckey)) {
443             BIO_printf(bio_err, "unable to generate key\n");
444             EC_KEY_free(eckey);
445             ERR_print_errors(bio_err);
446             goto end;
447         }
448         assert(private);
449         if (outformat == FORMAT_ASN1)
450             i = i2d_ECPrivateKey_bio(out, eckey);
451         else
452             i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
453                                            NULL, 0, NULL, NULL);
454         EC_KEY_free(eckey);
455     }
456
457     ret = 0;
458  end:
459     BN_free(ec_p);
460     BN_free(ec_a);
461     BN_free(ec_b);
462     BN_free(ec_gen);
463     BN_free(ec_order);
464     BN_free(ec_cofactor);
465     OPENSSL_free(buffer);
466     EC_GROUP_free(group);
467     release_engine(e);
468     BIO_free(in);
469     BIO_free_all(out);
470     return ret;
471 }