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