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