1/*
2 * Copyright 1999-2021 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 <stdlib.h>
12#include <string.h>
13#include "apps.h"
14#include "progs.h"
15#include <openssl/pem.h>
16#include <openssl/err.h>
17#include <openssl/evp.h>
18#include <openssl/pkcs12.h>
19
20typedef enum OPTION_choice {
21    OPT_COMMON,
22    OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT,
23    OPT_TOPK8, OPT_NOITER, OPT_NOCRYPT,
24#ifndef OPENSSL_NO_SCRYPT
25    OPT_SCRYPT, OPT_SCRYPT_N, OPT_SCRYPT_R, OPT_SCRYPT_P,
26#endif
27    OPT_V2, OPT_V1, OPT_V2PRF, OPT_ITER, OPT_PASSIN, OPT_PASSOUT,
28    OPT_TRADITIONAL,
29    OPT_R_ENUM, OPT_PROV_ENUM
30} OPTION_CHOICE;
31
32const OPTIONS pkcs8_options[] = {
33    OPT_SECTION("General"),
34    {"help", OPT_HELP, '-', "Display this summary"},
35#ifndef OPENSSL_NO_ENGINE
36    {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
37#endif
38    {"v1", OPT_V1, 's', "Use PKCS#5 v1.5 and cipher"},
39    {"v2", OPT_V2, 's', "Use PKCS#5 v2.0 and cipher"},
40    {"v2prf", OPT_V2PRF, 's', "Set the PRF algorithm to use with PKCS#5 v2.0"},
41
42    OPT_SECTION("Input"),
43    {"in", OPT_IN, '<', "Input file"},
44    {"inform", OPT_INFORM, 'F', "Input format (DER or PEM)"},
45    {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
46    {"nocrypt", OPT_NOCRYPT, '-', "Use or expect unencrypted private key"},
47
48    OPT_SECTION("Output"),
49    {"out", OPT_OUT, '>', "Output file"},
50    {"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"},
51    {"topk8", OPT_TOPK8, '-', "Output PKCS8 file"},
52    {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
53    {"traditional", OPT_TRADITIONAL, '-', "use traditional format private key"},
54    {"iter", OPT_ITER, 'p', "Specify the iteration count"},
55    {"noiter", OPT_NOITER, '-', "Use 1 as iteration count"},
56
57#ifndef OPENSSL_NO_SCRYPT
58    OPT_SECTION("Scrypt"),
59    {"scrypt", OPT_SCRYPT, '-', "Use scrypt algorithm"},
60    {"scrypt_N", OPT_SCRYPT_N, 's', "Set scrypt N parameter"},
61    {"scrypt_r", OPT_SCRYPT_R, 's', "Set scrypt r parameter"},
62    {"scrypt_p", OPT_SCRYPT_P, 's', "Set scrypt p parameter"},
63#endif
64
65    OPT_R_OPTIONS,
66    OPT_PROV_OPTIONS,
67    {NULL}
68};
69
70int pkcs8_main(int argc, char **argv)
71{
72    BIO *in = NULL, *out = NULL;
73    ENGINE *e = NULL;
74    EVP_PKEY *pkey = NULL;
75    PKCS8_PRIV_KEY_INFO *p8inf = NULL;
76    X509_SIG *p8 = NULL;
77    EVP_CIPHER *cipher = NULL;
78    char *infile = NULL, *outfile = NULL, *ciphername = NULL;
79    char *passinarg = NULL, *passoutarg = NULL, *prog;
80#ifndef OPENSSL_NO_UI_CONSOLE
81    char pass[APP_PASS_LEN];
82#endif
83    char *passin = NULL, *passout = NULL, *p8pass = NULL;
84    OPTION_CHOICE o;
85    int nocrypt = 0, ret = 1, iter = PKCS12_DEFAULT_ITER;
86    int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, topk8 = 0, pbe_nid = -1;
87    int private = 0, traditional = 0;
88#ifndef OPENSSL_NO_SCRYPT
89    long scrypt_N = 0, scrypt_r = 0, scrypt_p = 0;
90#endif
91
92    prog = opt_init(argc, argv, pkcs8_options);
93    while ((o = opt_next()) != OPT_EOF) {
94        switch (o) {
95        case OPT_EOF:
96        case OPT_ERR:
97 opthelp:
98            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
99            goto end;
100        case OPT_HELP:
101            opt_help(pkcs8_options);
102            ret = 0;
103            goto end;
104        case OPT_INFORM:
105            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
106                goto opthelp;
107            break;
108        case OPT_IN:
109            infile = opt_arg();
110            break;
111        case OPT_OUTFORM:
112            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
113                goto opthelp;
114            break;
115        case OPT_OUT:
116            outfile = opt_arg();
117            break;
118        case OPT_TOPK8:
119            topk8 = 1;
120            break;
121        case OPT_NOITER:
122            iter = 1;
123            break;
124        case OPT_NOCRYPT:
125            nocrypt = 1;
126            break;
127        case OPT_R_CASES:
128            if (!opt_rand(o))
129                goto end;
130            break;
131        case OPT_PROV_CASES:
132            if (!opt_provider(o))
133                goto end;
134            break;
135        case OPT_TRADITIONAL:
136            traditional = 1;
137            break;
138        case OPT_V2:
139            ciphername = opt_arg();
140            break;
141        case OPT_V1:
142            pbe_nid = OBJ_txt2nid(opt_arg());
143            if (pbe_nid == NID_undef) {
144                BIO_printf(bio_err,
145                           "%s: Unknown PBE algorithm %s\n", prog, opt_arg());
146                goto opthelp;
147            }
148            break;
149        case OPT_V2PRF:
150            pbe_nid = OBJ_txt2nid(opt_arg());
151            if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) {
152                BIO_printf(bio_err,
153                           "%s: Unknown PRF algorithm %s\n", prog, opt_arg());
154                goto opthelp;
155            }
156            if (cipher == NULL)
157                cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
158            break;
159        case OPT_ITER:
160            iter =  opt_int_arg();
161            break;
162        case OPT_PASSIN:
163            passinarg = opt_arg();
164            break;
165        case OPT_PASSOUT:
166            passoutarg = opt_arg();
167            break;
168        case OPT_ENGINE:
169            e = setup_engine(opt_arg(), 0);
170            break;
171#ifndef OPENSSL_NO_SCRYPT
172        case OPT_SCRYPT:
173            scrypt_N = 16384;
174            scrypt_r = 8;
175            scrypt_p = 1;
176            if (cipher == NULL)
177                cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
178            break;
179        case OPT_SCRYPT_N:
180            if (!opt_long(opt_arg(), &scrypt_N) || scrypt_N <= 0)
181                goto opthelp;
182            break;
183        case OPT_SCRYPT_R:
184            if (!opt_long(opt_arg(), &scrypt_r) || scrypt_r <= 0)
185                goto opthelp;
186            break;
187        case OPT_SCRYPT_P:
188            if (!opt_long(opt_arg(), &scrypt_p) || scrypt_p <= 0)
189                goto opthelp;
190            break;
191#endif
192        }
193    }
194
195    /* No extra arguments. */
196    argc = opt_num_rest();
197    if (argc != 0)
198        goto opthelp;
199
200    private = 1;
201    if (!app_RAND_load())
202        goto end;
203
204    if (ciphername != NULL) {
205        if (!opt_cipher(ciphername, &cipher))
206            goto opthelp;
207    }
208
209    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
210        BIO_printf(bio_err, "Error getting passwords\n");
211        goto end;
212    }
213
214    if ((pbe_nid == -1) && cipher == NULL)
215        cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
216
217    in = bio_open_default(infile, 'r',
218                          informat == FORMAT_UNDEF ? FORMAT_PEM : informat);
219    if (in == NULL)
220        goto end;
221    out = bio_open_owner(outfile, outformat, private);
222    if (out == NULL)
223        goto end;
224
225    if (topk8) {
226        pkey = load_key(infile, informat, 1, passin, e, "key");
227        if (pkey == NULL)
228            goto end;
229        if ((p8inf = EVP_PKEY2PKCS8(pkey)) == NULL) {
230            BIO_printf(bio_err, "Error converting key\n");
231            ERR_print_errors(bio_err);
232            goto end;
233        }
234        if (nocrypt) {
235            assert(private);
236            if (outformat == FORMAT_PEM) {
237                PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
238            } else if (outformat == FORMAT_ASN1) {
239                i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
240            } else {
241                BIO_printf(bio_err, "Bad format specified for key\n");
242                goto end;
243            }
244        } else {
245            X509_ALGOR *pbe;
246            if (cipher) {
247#ifndef OPENSSL_NO_SCRYPT
248                if (scrypt_N && scrypt_r && scrypt_p)
249                    pbe = PKCS5_pbe2_set_scrypt(cipher, NULL, 0, NULL,
250                                                scrypt_N, scrypt_r, scrypt_p);
251                else
252#endif
253                    pbe = PKCS5_pbe2_set_iv(cipher, iter, NULL, 0, NULL,
254                                            pbe_nid);
255            } else {
256                pbe = PKCS5_pbe_set(pbe_nid, iter, NULL, 0);
257            }
258            if (pbe == NULL) {
259                BIO_printf(bio_err, "Error setting PBE algorithm\n");
260                ERR_print_errors(bio_err);
261                goto end;
262            }
263            if (passout != NULL) {
264                p8pass = passout;
265            } else if (1) {
266                /* To avoid bit rot */
267#ifndef OPENSSL_NO_UI_CONSOLE
268                p8pass = pass;
269                if (EVP_read_pw_string
270                    (pass, sizeof(pass), "Enter Encryption Password:", 1)) {
271                    X509_ALGOR_free(pbe);
272                    goto end;
273                }
274            } else {
275#endif
276                BIO_printf(bio_err, "Password required\n");
277                goto end;
278            }
279            p8 = PKCS8_set0_pbe(p8pass, strlen(p8pass), p8inf, pbe);
280            if (p8 == NULL) {
281                X509_ALGOR_free(pbe);
282                BIO_printf(bio_err, "Error encrypting key\n");
283                ERR_print_errors(bio_err);
284                goto end;
285            }
286            assert(private);
287            if (outformat == FORMAT_PEM)
288                PEM_write_bio_PKCS8(out, p8);
289            else if (outformat == FORMAT_ASN1)
290                i2d_PKCS8_bio(out, p8);
291            else {
292                BIO_printf(bio_err, "Bad format specified for key\n");
293                goto end;
294            }
295        }
296
297        ret = 0;
298        goto end;
299    }
300
301    if (nocrypt) {
302        if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) {
303            p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
304        } else if (informat == FORMAT_ASN1) {
305            p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
306        } else {
307            BIO_printf(bio_err, "Bad format specified for key\n");
308            goto end;
309        }
310    } else {
311        if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) {
312            p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
313        } else if (informat == FORMAT_ASN1) {
314            p8 = d2i_PKCS8_bio(in, NULL);
315        } else {
316            BIO_printf(bio_err, "Bad format specified for key\n");
317            goto end;
318        }
319
320        if (p8 == NULL) {
321            BIO_printf(bio_err, "Error reading key\n");
322            ERR_print_errors(bio_err);
323            goto end;
324        }
325        if (passin != NULL) {
326            p8pass = passin;
327        } else if (1) {
328#ifndef OPENSSL_NO_UI_CONSOLE
329            p8pass = pass;
330            if (EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0)) {
331                BIO_printf(bio_err, "Can't read Password\n");
332                goto end;
333            }
334        } else {
335#endif
336            BIO_printf(bio_err, "Password required\n");
337            goto end;
338        }
339        p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
340    }
341
342    if (p8inf == NULL) {
343        BIO_printf(bio_err, "Error decrypting key\n");
344        ERR_print_errors(bio_err);
345        goto end;
346    }
347
348    if ((pkey = EVP_PKCS82PKEY(p8inf)) == NULL) {
349        BIO_printf(bio_err, "Error converting key\n");
350        ERR_print_errors(bio_err);
351        goto end;
352    }
353
354    assert(private);
355    if (outformat == FORMAT_PEM) {
356        if (traditional)
357            PEM_write_bio_PrivateKey_traditional(out, pkey, NULL, NULL, 0,
358                                                 NULL, passout);
359        else
360            PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
361    } else if (outformat == FORMAT_ASN1) {
362        i2d_PrivateKey_bio(out, pkey);
363    } else {
364        BIO_printf(bio_err, "Bad format specified for key\n");
365        goto end;
366    }
367    ret = 0;
368
369 end:
370    X509_SIG_free(p8);
371    PKCS8_PRIV_KEY_INFO_free(p8inf);
372    EVP_PKEY_free(pkey);
373    EVP_CIPHER_free(cipher);
374    release_engine(e);
375    BIO_free_all(out);
376    BIO_free(in);
377    OPENSSL_free(passin);
378    OPENSSL_free(passout);
379
380    return ret;
381}
382