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