1/*
2 * Copyright 2006-2023 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (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#include <stdio.h>
11#include <string.h>
12#include "apps.h"
13#include "progs.h"
14#include "ec_common.h"
15#include <openssl/pem.h>
16#include <openssl/err.h>
17#include <openssl/evp.h>
18#include <openssl/core_names.h>
19
20typedef enum OPTION_choice {
21    OPT_COMMON,
22    OPT_INFORM, OPT_OUTFORM, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE,
23    OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_TEXT_PUB,
24    OPT_TEXT, OPT_NOOUT, OPT_CIPHER, OPT_TRADITIONAL, OPT_CHECK, OPT_PUB_CHECK,
25    OPT_EC_PARAM_ENC, OPT_EC_CONV_FORM,
26    OPT_PROV_ENUM
27} OPTION_CHOICE;
28
29const OPTIONS pkey_options[] = {
30    OPT_SECTION("General"),
31    {"help", OPT_HELP, '-', "Display this summary"},
32#ifndef OPENSSL_NO_ENGINE
33    {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
34#endif
35    OPT_PROV_OPTIONS,
36
37    {"check", OPT_CHECK, '-', "Check key consistency"},
38    {"pubcheck", OPT_PUB_CHECK, '-', "Check public key consistency"},
39
40    OPT_SECTION("Input"),
41    {"in", OPT_IN, 's', "Input key"},
42    {"inform", OPT_INFORM, 'f',
43     "Key input format (ENGINE, other values ignored)"},
44    {"passin", OPT_PASSIN, 's', "Key input pass phrase source"},
45    {"pubin", OPT_PUBIN, '-',
46     "Read only public components from key input"},
47
48    OPT_SECTION("Output"),
49    {"out", OPT_OUT, '>', "Output file for encoded and/or text output"},
50    {"outform", OPT_OUTFORM, 'F', "Output encoding format (DER or PEM)"},
51    {"", OPT_CIPHER, '-', "Any supported cipher to be used for encryption"},
52    {"passout", OPT_PASSOUT, 's', "Output PEM file pass phrase source"},
53    {"traditional", OPT_TRADITIONAL, '-',
54     "Use traditional format for private key PEM output"},
55    {"pubout", OPT_PUBOUT, '-', "Restrict encoded output to public components"},
56    {"noout", OPT_NOOUT, '-', "Do not output the key in encoded form"},
57    {"text", OPT_TEXT, '-', "Output key components in plaintext"},
58    {"text_pub", OPT_TEXT_PUB, '-',
59     "Output only public key components in text form"},
60    {"ec_conv_form", OPT_EC_CONV_FORM, 's',
61     "Specifies the EC point conversion form in the encoding"},
62    {"ec_param_enc", OPT_EC_PARAM_ENC, 's',
63     "Specifies the way the EC parameters are encoded"},
64
65    {NULL}
66};
67
68int pkey_main(int argc, char **argv)
69{
70    BIO *out = NULL;
71    ENGINE *e = NULL;
72    EVP_PKEY *pkey = NULL;
73    EVP_PKEY_CTX *ctx = NULL;
74    EVP_CIPHER *cipher = NULL;
75    char *infile = NULL, *outfile = NULL, *passin = NULL, *passout = NULL;
76    char *passinarg = NULL, *passoutarg = NULL, *ciphername = NULL, *prog;
77    OPTION_CHOICE o;
78    int informat = FORMAT_UNDEF, outformat = FORMAT_PEM;
79    int pubin = 0, pubout = 0, text_pub = 0, text = 0, noout = 0, ret = 1;
80    int private = 0, traditional = 0, check = 0, pub_check = 0;
81#ifndef OPENSSL_NO_EC
82    char *asn1_encoding = NULL;
83    char *point_format = NULL;
84#endif
85
86    prog = opt_init(argc, argv, pkey_options);
87    while ((o = opt_next()) != OPT_EOF) {
88        switch (o) {
89        case OPT_EOF:
90        case OPT_ERR:
91 opthelp:
92            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
93            goto end;
94        case OPT_HELP:
95            opt_help(pkey_options);
96            ret = 0;
97            goto end;
98        case OPT_INFORM:
99            if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
100                goto opthelp;
101            break;
102        case OPT_OUTFORM:
103            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
104                goto opthelp;
105            break;
106        case OPT_PASSIN:
107            passinarg = opt_arg();
108            break;
109        case OPT_PASSOUT:
110            passoutarg = opt_arg();
111            break;
112        case OPT_ENGINE:
113            e = setup_engine(opt_arg(), 0);
114            break;
115        case OPT_IN:
116            infile = opt_arg();
117            break;
118        case OPT_OUT:
119            outfile = opt_arg();
120            break;
121        case OPT_PUBIN:
122            pubin = pubout = 1;
123            break;
124        case OPT_PUBOUT:
125            pubout = 1;
126            break;
127        case OPT_TEXT_PUB:
128            text_pub = 1;
129            break;
130        case OPT_TEXT:
131            text = 1;
132            break;
133        case OPT_NOOUT:
134            noout = 1;
135            break;
136        case OPT_TRADITIONAL:
137            traditional = 1;
138            break;
139        case OPT_CHECK:
140            check = 1;
141            break;
142        case OPT_PUB_CHECK:
143            pub_check = 1;
144            break;
145        case OPT_CIPHER:
146            ciphername = opt_unknown();
147            break;
148        case OPT_EC_CONV_FORM:
149#ifdef OPENSSL_NO_EC
150            goto opthelp;
151#else
152            point_format = opt_arg();
153            if (!opt_string(point_format, point_format_options))
154                goto opthelp;
155            break;
156#endif
157        case OPT_EC_PARAM_ENC:
158#ifdef OPENSSL_NO_EC
159            goto opthelp;
160#else
161            asn1_encoding = opt_arg();
162            if (!opt_string(asn1_encoding, asn1_encoding_options))
163                goto opthelp;
164            break;
165#endif
166        case OPT_PROV_CASES:
167            if (!opt_provider(o))
168                goto end;
169            break;
170        }
171    }
172
173    /* No extra arguments. */
174    argc = opt_num_rest();
175    if (argc != 0)
176        goto opthelp;
177
178    if (text && text_pub)
179        BIO_printf(bio_err,
180                   "Warning: The -text option is ignored with -text_pub\n");
181    if (traditional && (noout || outformat != FORMAT_PEM))
182        BIO_printf(bio_err,
183                   "Warning: The -traditional is ignored since there is no PEM output\n");
184
185    /* -pubout and -text is the same as -text_pub */
186    if (!text_pub && pubout && text) {
187        text = 0;
188        text_pub = 1;
189    }
190
191    private = (!noout && !pubout) || (text && !text_pub);
192
193    if (ciphername != NULL) {
194        if (!opt_cipher(ciphername, &cipher))
195            goto opthelp;
196    }
197    if (cipher == NULL) {
198        if (passoutarg != NULL)
199            BIO_printf(bio_err,
200                       "Warning: The -passout option is ignored without a cipher option\n");
201    } else {
202        if (noout || outformat != FORMAT_PEM) {
203            BIO_printf(bio_err,
204                       "Error: Cipher options are supported only for PEM output\n");
205            goto end;
206        }
207    }
208    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
209        BIO_printf(bio_err, "Error getting passwords\n");
210        goto end;
211    }
212
213    out = bio_open_owner(outfile, outformat, private);
214    if (out == NULL)
215        goto end;
216
217    if (pubin)
218        pkey = load_pubkey(infile, informat, 1, passin, e, "Public Key");
219    else
220        pkey = load_key(infile, informat, 1, passin, e, "key");
221    if (pkey == NULL)
222        goto end;
223
224#ifndef OPENSSL_NO_EC
225    if (asn1_encoding != NULL || point_format != NULL) {
226        OSSL_PARAM params[3], *p = params;
227
228        if (!EVP_PKEY_is_a(pkey, "EC"))
229            goto end;
230
231        if (asn1_encoding != NULL)
232            *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING,
233                                                    asn1_encoding, 0);
234        if (point_format != NULL)
235            *p++ = OSSL_PARAM_construct_utf8_string(
236                       OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
237                       point_format, 0);
238        *p = OSSL_PARAM_construct_end();
239        if (EVP_PKEY_set_params(pkey, params) <= 0)
240            goto end;
241    }
242#endif
243
244    if (check || pub_check) {
245        int r;
246
247        ctx = EVP_PKEY_CTX_new(pkey, e);
248        if (ctx == NULL) {
249            ERR_print_errors(bio_err);
250            goto end;
251        }
252
253        if (check && !pubin)
254            r = EVP_PKEY_check(ctx);
255        else
256            r = EVP_PKEY_public_check(ctx);
257
258        if (r == 1) {
259            BIO_printf(out, "Key is valid\n");
260        } else {
261            /*
262             * Note: at least for RSA keys if this function returns
263             * -1, there will be no error reasons.
264             */
265            BIO_printf(bio_err, "Key is invalid\n");
266            ERR_print_errors(bio_err);
267            goto end;
268        }
269    }
270
271    if (!noout) {
272        if (outformat == FORMAT_PEM) {
273            if (pubout) {
274                if (!PEM_write_bio_PUBKEY(out, pkey))
275                    goto end;
276            } else {
277                assert(private);
278                if (traditional) {
279                    if (!PEM_write_bio_PrivateKey_traditional(out, pkey, cipher,
280                                                              NULL, 0, NULL,
281                                                              passout))
282                        goto end;
283                } else {
284                    if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
285                                                  NULL, 0, NULL, passout))
286                        goto end;
287                }
288            }
289        } else if (outformat == FORMAT_ASN1) {
290            if (text || text_pub) {
291                BIO_printf(bio_err,
292                           "Error: Text output cannot be combined with DER output\n");
293                goto end;
294            }
295            if (pubout) {
296                if (!i2d_PUBKEY_bio(out, pkey))
297                    goto end;
298            } else {
299                assert(private);
300                if (!i2d_PrivateKey_bio(out, pkey))
301                    goto end;
302            }
303        } else {
304            BIO_printf(bio_err, "Bad format specified for key\n");
305            goto end;
306        }
307    }
308
309    if (text_pub) {
310        if (EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0)
311            goto end;
312    } else if (text) {
313        assert(private);
314        if (EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)
315            goto end;
316    }
317
318    ret = 0;
319
320 end:
321    if (ret != 0)
322        ERR_print_errors(bio_err);
323    EVP_PKEY_CTX_free(ctx);
324    EVP_PKEY_free(pkey);
325    EVP_CIPHER_free(cipher);
326    release_engine(e);
327    BIO_free_all(out);
328    OPENSSL_free(passin);
329    OPENSSL_free(passout);
330
331    return ret;
332}
333