Convert uses of snprintf to BIO_snprintf
[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 const 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     ENGINE *e = NULL;
91     BIGNUM *ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL;
92     BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL;
93     BIO *in = NULL, *out = NULL;
94     EC_GROUP *group = NULL;
95     point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED;
96     char *curve_name = NULL, *inrand = NULL;
97     char *infile = NULL, *outfile = NULL, *prog;
98     unsigned char *buffer = NULL;
99     OPTION_CHOICE o;
100     int asn1_flag = OPENSSL_EC_NAMED_CURVE, new_asn1_flag = 0;
101     int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0;
102     int ret = 1, private = 0;
103     int list_curves = 0, no_seed = 0, check = 0, new_form = 0;
104     int text = 0, i, need_rand = 0, genkey = 0;
105
106     prog = opt_init(argc, argv, ecparam_options);
107     while ((o = opt_next()) != OPT_EOF) {
108         switch (o) {
109         case OPT_EOF:
110         case OPT_ERR:
111  opthelp:
112             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
113             goto end;
114         case OPT_HELP:
115             opt_help(ecparam_options);
116             ret = 0;
117             goto end;
118         case OPT_INFORM:
119             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
120                 goto opthelp;
121             break;
122         case OPT_IN:
123             infile = opt_arg();
124             break;
125         case OPT_OUTFORM:
126             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
127                 goto opthelp;
128             break;
129         case OPT_OUT:
130             outfile = opt_arg();
131             break;
132         case OPT_TEXT:
133             text = 1;
134             break;
135         case OPT_C:
136             C = 1;
137             break;
138         case OPT_CHECK:
139             check = 1;
140             break;
141         case OPT_LIST_CURVES:
142             list_curves = 1;
143             break;
144         case OPT_NO_SEED:
145             no_seed = 1;
146             break;
147         case OPT_NOOUT:
148             noout = 1;
149             break;
150         case OPT_NAME:
151             curve_name = opt_arg();
152             break;
153         case OPT_CONV_FORM:
154             if (!opt_pair(opt_arg(), forms, &new_form))
155                 goto opthelp;
156             form = new_form;
157             new_form = 1;
158             break;
159         case OPT_PARAM_ENC:
160             if (!opt_pair(opt_arg(), encodings, &asn1_flag))
161                 goto opthelp;
162             new_asn1_flag = 1;
163             break;
164         case OPT_GENKEY:
165             genkey = need_rand = 1;
166             break;
167         case OPT_RAND:
168             inrand = opt_arg();
169             need_rand = 1;
170             break;
171         case OPT_ENGINE:
172             e = setup_engine(opt_arg(), 0);
173             break;
174         }
175     }
176     argc = opt_num_rest();
177     if (argc != 0)
178         goto opthelp;
179
180     private = genkey ? 1 : 0;
181
182     in = bio_open_default(infile, 'r', informat);
183     if (in == NULL)
184         goto end;
185     out = bio_open_owner(outfile, outformat, private);
186     if (out == NULL)
187         goto end;
188
189     if (list_curves) {
190         EC_builtin_curve *curves = NULL;
191         size_t crv_len = EC_get_builtin_curves(NULL, 0);
192         size_t n;
193
194         curves = app_malloc((int)sizeof(*curves) * crv_len, "list curves");
195         if (!EC_get_builtin_curves(curves, crv_len)) {
196             OPENSSL_free(curves);
197             goto end;
198         }
199
200         for (n = 0; n < crv_len; n++) {
201             const char *comment;
202             const char *sname;
203             comment = curves[n].comment;
204             sname = OBJ_nid2sn(curves[n].nid);
205             if (comment == NULL)
206                 comment = "CURVE DESCRIPTION NOT AVAILABLE";
207             if (sname == NULL)
208                 sname = "";
209
210             BIO_printf(out, "  %-10s: ", sname);
211             BIO_printf(out, "%s\n", comment);
212         }
213
214         OPENSSL_free(curves);
215         ret = 0;
216         goto end;
217     }
218
219     if (curve_name != NULL) {
220         int nid;
221
222         /*
223          * workaround for the SECG curve names secp192r1 and secp256r1 (which
224          * are the same as the curves prime192v1 and prime256v1 defined in
225          * X9.62)
226          */
227         if (strcmp(curve_name, "secp192r1") == 0) {
228             BIO_printf(bio_err, "using curve name prime192v1 "
229                        "instead of secp192r1\n");
230             nid = NID_X9_62_prime192v1;
231         } else if (strcmp(curve_name, "secp256r1") == 0) {
232             BIO_printf(bio_err, "using curve name prime256v1 "
233                        "instead of secp256r1\n");
234             nid = NID_X9_62_prime256v1;
235         } else
236             nid = OBJ_sn2nid(curve_name);
237
238         if (nid == 0)
239             nid = EC_curve_nist2nid(curve_name);
240
241         if (nid == 0) {
242             BIO_printf(bio_err, "unknown curve name (%s)\n", curve_name);
243             goto end;
244         }
245
246         group = EC_GROUP_new_by_curve_name(nid);
247         if (group == NULL) {
248             BIO_printf(bio_err, "unable to create curve (%s)\n", curve_name);
249             goto end;
250         }
251         EC_GROUP_set_asn1_flag(group, asn1_flag);
252         EC_GROUP_set_point_conversion_form(group, form);
253     } else if (informat == FORMAT_ASN1)
254         group = d2i_ECPKParameters_bio(in, NULL);
255     else
256         group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL);
257     if (group == NULL) {
258         BIO_printf(bio_err, "unable to load elliptic curve parameters\n");
259         ERR_print_errors(bio_err);
260         goto end;
261     }
262
263     if (new_form)
264         EC_GROUP_set_point_conversion_form(group, form);
265
266     if (new_asn1_flag)
267         EC_GROUP_set_asn1_flag(group, asn1_flag);
268
269     if (no_seed) {
270         EC_GROUP_set_seed(group, NULL, 0);
271     }
272
273     if (text) {
274         if (!ECPKParameters_print(out, group, 0))
275             goto end;
276     }
277
278     if (check) {
279         BIO_printf(bio_err, "checking elliptic curve parameters: ");
280         if (!EC_GROUP_check(group, NULL)) {
281             BIO_printf(bio_err, "failed\n");
282             ERR_print_errors(bio_err);
283             goto end;
284         }
285         BIO_printf(bio_err, "ok\n");
286
287     }
288
289     if (C) {
290         size_t buf_len = 0, tmp_len = 0;
291         const EC_POINT *point;
292         int is_prime, len = 0;
293         const EC_METHOD *meth = EC_GROUP_method_of(group);
294
295         if ((ec_p = BN_new()) == NULL
296                 || (ec_a = BN_new()) == NULL
297                 || (ec_b = BN_new()) == NULL
298                 || (ec_gen = BN_new()) == NULL
299                 || (ec_order = BN_new()) == NULL
300                 || (ec_cofactor = BN_new()) == NULL) {
301             perror("Can't allocate BN");
302             goto end;
303         }
304
305         is_prime = (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field);
306         if (!is_prime) {
307             BIO_printf(bio_err, "Can only handle X9.62 prime fields\n");
308             goto end;
309         }
310
311         if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a, ec_b, NULL))
312             goto end;
313
314         if ((point = EC_GROUP_get0_generator(group)) == NULL)
315             goto end;
316         if (!EC_POINT_point2bn(group, point,
317                                EC_GROUP_get_point_conversion_form(group),
318                                ec_gen, NULL))
319             goto end;
320         if (!EC_GROUP_get_order(group, ec_order, NULL))
321             goto end;
322         if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL))
323             goto end;
324
325         if (!ec_p || !ec_a || !ec_b || !ec_gen || !ec_order || !ec_cofactor)
326             goto end;
327
328         len = BN_num_bits(ec_order);
329
330         if ((tmp_len = (size_t)BN_num_bytes(ec_p)) > buf_len)
331             buf_len = tmp_len;
332         if ((tmp_len = (size_t)BN_num_bytes(ec_a)) > buf_len)
333             buf_len = tmp_len;
334         if ((tmp_len = (size_t)BN_num_bytes(ec_b)) > buf_len)
335             buf_len = tmp_len;
336         if ((tmp_len = (size_t)BN_num_bytes(ec_gen)) > buf_len)
337             buf_len = tmp_len;
338         if ((tmp_len = (size_t)BN_num_bytes(ec_order)) > buf_len)
339             buf_len = tmp_len;
340         if ((tmp_len = (size_t)BN_num_bytes(ec_cofactor)) > buf_len)
341             buf_len = tmp_len;
342
343         buffer = app_malloc(buf_len, "BN buffer");
344
345         BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n{\n", len);
346         print_bignum_var(out, ec_p, "ec_p", len, buffer);
347         print_bignum_var(out, ec_a, "ec_a", len, buffer);
348         print_bignum_var(out, ec_b, "ec_b", len, buffer);
349         print_bignum_var(out, ec_gen, "ec_gen", len, buffer);
350         print_bignum_var(out, ec_order, "ec_order", len, buffer);
351         print_bignum_var(out, ec_cofactor, "ec_cofactor", len, buffer);
352         BIO_printf(out, "    int ok = 0;\n"
353                         "    EC_GROUP *group = NULL;\n"
354                         "    EC_POINT *point = NULL;\n"
355                         "    BIGNUM *tmp_1 = NULL;\n"
356                         "    BIGNUM *tmp_2 = NULL;\n"
357                         "    BIGNUM *tmp_3 = NULL;\n"
358                         "\n");
359
360         BIO_printf(out, "    if ((tmp_1 = BN_bin2bn(ec_p_%d, sizeof (ec_p_%d), NULL)) == NULL)\n"
361                         "        goto err;\n", len, len);
362         BIO_printf(out, "    if ((tmp_2 = BN_bin2bn(ec_a_%d, sizeof (ec_a_%d), NULL)) == NULL)\n"
363                         "        goto err;\n", len, len);
364         BIO_printf(out, "    if ((tmp_3 = BN_bin2bn(ec_b_%d, sizeof (ec_b_%d), NULL)) == NULL)\n"
365                         "        goto err;\n", len, len);
366         BIO_printf(out, "    if ((group = EC_GROUP_new_curve_GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)\n"
367                         "        goto err;\n"
368                         "\n");
369         BIO_printf(out, "    /* build generator */\n");
370         BIO_printf(out, "    if ((tmp_1 = BN_bin2bn(ec_gen_%d, sizeof (ec_gen_%d), tmp_1)) == NULL)\n"
371                         "        goto err;\n", len, len);
372         BIO_printf(out, "    point = EC_POINT_bn2point(group, tmp_1, NULL, NULL);\n");
373         BIO_printf(out, "    if (point == NULL)\n"
374                         "        goto err;\n");
375         BIO_printf(out, "    if ((tmp_2 = BN_bin2bn(ec_order_%d, sizeof (ec_order_%d), tmp_2)) == NULL)\n"
376                         "        goto err;\n", len, len);
377         BIO_printf(out, "    if ((tmp_3 = BN_bin2bn(ec_cofactor_%d, sizeof (ec_cofactor_%d), tmp_3)) == NULL)\n"
378                         "        goto err;\n", len, len);
379         BIO_printf(out, "    if (!EC_GROUP_set_generator(group, point, tmp_2, tmp_3))\n"
380                         "        goto err;\n"
381                         "ok = 1;"
382                         "\n");
383         BIO_printf(out, "err:\n"
384                         "    BN_free(tmp_1);\n"
385                         "    BN_free(tmp_2);\n"
386                         "    BN_free(tmp_3);\n"
387                         "    EC_POINT_free(point);\n"
388                         "    if (!ok) {\n"
389                         "        EC_GROUP_free(group);\n"
390                         "        return NULL;\n"
391                         "    }\n"
392                         "    return (group);\n"
393                         "}\n");
394     }
395
396     if (!noout) {
397         if (outformat == FORMAT_ASN1)
398             i = i2d_ECPKParameters_bio(out, group);
399         else
400             i = PEM_write_bio_ECPKParameters(out, group);
401         if (!i) {
402             BIO_printf(bio_err, "unable to write elliptic "
403                        "curve parameters\n");
404             ERR_print_errors(bio_err);
405             goto end;
406         }
407     }
408
409     if (need_rand) {
410         app_RAND_load_file(NULL, (inrand != NULL));
411         if (inrand != NULL)
412             BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
413                        app_RAND_load_files(inrand));
414     }
415
416     if (genkey) {
417         EC_KEY *eckey = EC_KEY_new();
418
419         if (eckey == NULL)
420             goto end;
421
422         assert(need_rand);
423
424         if (EC_KEY_set_group(eckey, group) == 0) {
425             BIO_printf(bio_err, "unable to set group when generating key\n");
426             EC_KEY_free(eckey);
427             ERR_print_errors(bio_err);
428             goto end;
429         }
430
431         if (!EC_KEY_generate_key(eckey)) {
432             BIO_printf(bio_err, "unable to generate key\n");
433             EC_KEY_free(eckey);
434             ERR_print_errors(bio_err);
435             goto end;
436         }
437         assert(private);
438         if (outformat == FORMAT_ASN1)
439             i = i2d_ECPrivateKey_bio(out, eckey);
440         else
441             i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
442                                            NULL, 0, NULL, NULL);
443         EC_KEY_free(eckey);
444     }
445
446     if (need_rand)
447         app_RAND_write_file(NULL);
448
449     ret = 0;
450  end:
451     BN_free(ec_p);
452     BN_free(ec_a);
453     BN_free(ec_b);
454     BN_free(ec_gen);
455     BN_free(ec_order);
456     BN_free(ec_cofactor);
457     OPENSSL_free(buffer);
458     EC_GROUP_free(group);
459     release_engine(e);
460     BIO_free(in);
461     BIO_free_all(out);
462     return (ret);
463 }
464
465 #endif