APPS/cmp: Simplify read_write_req_resp() - 'req' arg must not be NULL anyway
[openssl.git] / apps / rsa.c
1 /*
2  * Copyright 1995-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 /* Necessary for legacy RSA public key export */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <openssl/opensslconf.h>
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <time.h>
19 #include "apps.h"
20 #include "progs.h"
21 #include <openssl/bio.h>
22 #include <openssl/err.h>
23 #include <openssl/rsa.h>
24 #include <openssl/evp.h>
25 #include <openssl/x509.h>
26 #include <openssl/pem.h>
27 #include <openssl/bn.h>
28 #include <openssl/encoder.h>
29
30 /*
31  * This include is to get OSSL_KEYMGMT_SELECT_*, which feels a bit
32  * much just for those macros...  they might serve better as EVP macros.
33  */
34 #include <openssl/core_dispatch.h>
35
36 #ifndef OPENSSL_NO_RC4
37 # define DEFAULT_PVK_ENCR_STRENGTH      2
38 #else
39 # define DEFAULT_PVK_ENCR_STRENGTH      0
40 #endif
41
42 typedef enum OPTION_choice {
43     OPT_COMMON,
44     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT,
45     OPT_PUBIN, OPT_PUBOUT, OPT_PASSOUT, OPT_PASSIN,
46     OPT_RSAPUBKEY_IN, OPT_RSAPUBKEY_OUT,
47     /* Do not change the order here; see case statements below */
48     OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG,
49     OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_CHECK, OPT_CIPHER,
50     OPT_PROV_ENUM, OPT_TRADITIONAL
51 } OPTION_CHOICE;
52
53 const OPTIONS rsa_options[] = {
54     OPT_SECTION("General"),
55     {"help", OPT_HELP, '-', "Display this summary"},
56     {"check", OPT_CHECK, '-', "Verify key consistency"},
57     {"", OPT_CIPHER, '-', "Any supported cipher"},
58 #ifndef OPENSSL_NO_ENGINE
59     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
60 #endif
61
62     OPT_SECTION("Input"),
63     {"in", OPT_IN, 's', "Input file"},
64     {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE"},
65     {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"},
66     {"RSAPublicKey_in", OPT_RSAPUBKEY_IN, '-', "Input is an RSAPublicKey"},
67     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
68
69     OPT_SECTION("Output"),
70     {"out", OPT_OUT, '>', "Output file"},
71     {"outform", OPT_OUTFORM, 'f', "Output format, one of DER PEM PVK"},
72     {"pubout", OPT_PUBOUT, '-', "Output a public key"},
73     {"RSAPublicKey_out", OPT_RSAPUBKEY_OUT, '-', "Output is an RSAPublicKey"},
74     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
75     {"noout", OPT_NOOUT, '-', "Don't print key out"},
76     {"text", OPT_TEXT, '-', "Print the key in text"},
77     {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"},
78     {"traditional", OPT_TRADITIONAL, '-',
79      "Use traditional format for private keys"},
80
81 #ifndef OPENSSL_NO_RC4
82     OPT_SECTION("PVK"),
83     {"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"},
84     {"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"},
85     {"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"},
86 #endif
87
88     OPT_PROV_OPTIONS,
89     {NULL}
90 };
91
92 static int try_legacy_encoding(EVP_PKEY *pkey, int outformat, int pubout,
93                                BIO *out)
94 {
95     int ret = 0;
96 #ifndef OPENSSL_NO_DEPRECATED_3_0
97     const RSA *rsa = EVP_PKEY_get0_RSA(pkey);
98
99     if (rsa == NULL)
100         return 0;
101
102     if (outformat == FORMAT_ASN1) {
103         if (pubout == 2)
104             ret = i2d_RSAPublicKey_bio(out, rsa) > 0;
105         else
106             ret = i2d_RSA_PUBKEY_bio(out, rsa) > 0;
107     } else if (outformat == FORMAT_PEM) {
108         if (pubout == 2)
109             ret = PEM_write_bio_RSAPublicKey(out, rsa) > 0;
110         else
111             ret = PEM_write_bio_RSA_PUBKEY(out, rsa) > 0;
112 # ifndef OPENSSL_NO_DSA
113     } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) {
114         ret = i2b_PublicKey_bio(out, pkey) > 0;
115 # endif
116     }
117 #endif
118
119     return ret;
120 }
121
122 int rsa_main(int argc, char **argv)
123 {
124     ENGINE *e = NULL;
125     BIO *out = NULL;
126     EVP_PKEY *pkey = NULL;
127     EVP_PKEY_CTX *pctx;
128     EVP_CIPHER *enc = NULL;
129     char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog;
130     char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL;
131     int private = 0;
132     int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, check = 0;
133     int noout = 0, modulus = 0, pubin = 0, pubout = 0, ret = 1;
134     int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH;
135     OPTION_CHOICE o;
136     int traditional = 0;
137     const char *output_type = NULL;
138     const char *output_structure = NULL;
139     int selection = 0;
140     OSSL_ENCODER_CTX *ectx = NULL;
141
142     prog = opt_init(argc, argv, rsa_options);
143     while ((o = opt_next()) != OPT_EOF) {
144         switch (o) {
145         case OPT_EOF:
146         case OPT_ERR:
147  opthelp:
148             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
149             goto end;
150         case OPT_HELP:
151             opt_help(rsa_options);
152             ret = 0;
153             goto end;
154         case OPT_INFORM:
155             if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
156                 goto opthelp;
157             break;
158         case OPT_IN:
159             infile = opt_arg();
160             break;
161         case OPT_OUTFORM:
162             if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
163                 goto opthelp;
164             break;
165         case OPT_OUT:
166             outfile = opt_arg();
167             break;
168         case OPT_PASSIN:
169             passinarg = opt_arg();
170             break;
171         case OPT_PASSOUT:
172             passoutarg = opt_arg();
173             break;
174         case OPT_ENGINE:
175             e = setup_engine(opt_arg(), 0);
176             break;
177         case OPT_PUBIN:
178             pubin = 1;
179             break;
180         case OPT_PUBOUT:
181             pubout = 1;
182             break;
183         case OPT_RSAPUBKEY_IN:
184             pubin = 2;
185             break;
186         case OPT_RSAPUBKEY_OUT:
187             pubout = 2;
188             break;
189         case OPT_PVK_STRONG:    /* pvk_encr:= 2 */
190         case OPT_PVK_WEAK:      /* pvk_encr:= 1 */
191         case OPT_PVK_NONE:      /* pvk_encr:= 0 */
192             pvk_encr = (o - OPT_PVK_NONE);
193             break;
194         case OPT_NOOUT:
195             noout = 1;
196             break;
197         case OPT_TEXT:
198             text = 1;
199             break;
200         case OPT_MODULUS:
201             modulus = 1;
202             break;
203         case OPT_CHECK:
204             check = 1;
205             break;
206         case OPT_CIPHER:
207             ciphername = opt_unknown();
208             break;
209         case OPT_PROV_CASES:
210             if (!opt_provider(o))
211                 goto end;
212             break;
213         case OPT_TRADITIONAL:
214             traditional = 1;
215             break;
216         }
217     }
218
219     /* No extra arguments. */
220     if (!opt_check_rest_arg(NULL))
221         goto opthelp;
222
223     if (!opt_cipher(ciphername, &enc))
224         goto opthelp;
225     private = (text && !pubin) || (!pubout && !noout) ? 1 : 0;
226
227     if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
228         BIO_printf(bio_err, "Error getting passwords\n");
229         goto end;
230     }
231     if (check && pubin) {
232         BIO_printf(bio_err, "Only private keys can be checked\n");
233         goto end;
234     }
235
236     if (pubin) {
237         int tmpformat = FORMAT_UNDEF;
238
239         if (pubin == 2) {
240             if (informat == FORMAT_PEM)
241                 tmpformat = FORMAT_PEMRSA;
242             else if (informat == FORMAT_ASN1)
243                 tmpformat = FORMAT_ASN1RSA;
244         } else {
245             tmpformat = informat;
246         }
247
248         pkey = load_pubkey(infile, tmpformat, 1, passin, e, "public key");
249     } else {
250         pkey = load_key(infile, informat, 1, passin, e, "private key");
251     }
252
253     if (pkey == NULL) {
254         ERR_print_errors(bio_err);
255         goto end;
256     }
257     if (!EVP_PKEY_is_a(pkey, "RSA")) {
258         BIO_printf(bio_err, "Not an RSA key\n");
259         goto end;
260     }
261
262     out = bio_open_owner(outfile, outformat, private);
263     if (out == NULL)
264         goto end;
265
266     if (text) {
267         assert(pubin || private);
268         if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0)
269             || (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) {
270             perror(outfile);
271             ERR_print_errors(bio_err);
272             goto end;
273         }
274     }
275
276     if (modulus) {
277         BIGNUM *n = NULL;
278
279         /* Every RSA key has an 'n' */
280         EVP_PKEY_get_bn_param(pkey, "n", &n);
281         BIO_printf(out, "Modulus=");
282         BN_print(out, n);
283         BIO_printf(out, "\n");
284         BN_free(n);
285     }
286
287     if (check) {
288         int r;
289
290         pctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL);
291         if (pctx == NULL) {
292             BIO_printf(bio_err, "RSA unable to create PKEY context\n");
293             ERR_print_errors(bio_err);
294             goto end;
295         }
296         r = EVP_PKEY_check(pctx);
297         EVP_PKEY_CTX_free(pctx);
298
299         if (r == 1) {
300             BIO_printf(out, "RSA key ok\n");
301         } else if (r == 0) {
302             BIO_printf(bio_err, "RSA key not ok\n");
303             ERR_print_errors(bio_err);
304         } else if (r == -1) {
305             ERR_print_errors(bio_err);
306             goto end;
307         }
308     }
309
310     if (noout) {
311         ret = 0;
312         goto end;
313     }
314     BIO_printf(bio_err, "writing RSA key\n");
315
316     /* Choose output type for the format */
317     if (outformat == FORMAT_ASN1) {
318         output_type = "DER";
319     } else if (outformat == FORMAT_PEM) {
320         output_type = "PEM";
321     } else if (outformat == FORMAT_MSBLOB) {
322         output_type = "MSBLOB";
323     } else if (outformat == FORMAT_PVK) {
324         if (pubin) {
325             BIO_printf(bio_err, "PVK form impossible with public key input\n");
326             goto end;
327         }
328         output_type = "PVK";
329     } else {
330         BIO_printf(bio_err, "bad output format specified for outfile\n");
331         goto end;
332     }
333
334     /* Select what you want in the output */
335     if (pubout || pubin) {
336         selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
337     } else {
338         assert(private);
339         selection = (OSSL_KEYMGMT_SELECT_KEYPAIR
340                      | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS);
341     }
342
343     /* For DER based output, select the desired output structure */
344     if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) {
345         if (pubout || pubin) {
346             if (pubout == 2)
347                 output_structure = "pkcs1"; /* "type-specific" would work too */
348             else
349                 output_structure = "SubjectPublicKeyInfo";
350         } else {
351             assert(private);
352             if (traditional)
353                 output_structure = "pkcs1"; /* "type-specific" would work too */
354             else
355                 output_structure = "PrivateKeyInfo";
356         }
357     }
358
359     /* Now, perform the encoding */
360     ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection,
361                                          output_type, output_structure,
362                                          NULL);
363     if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) {
364         if ((!pubout && !pubin)
365             || !try_legacy_encoding(pkey, outformat, pubout, out))
366             BIO_printf(bio_err, "%s format not supported\n", output_type);
367         else
368             ret = 0;
369         goto end;
370     }
371
372     /* Passphrase setup */
373     if (enc != NULL)
374         OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL);
375
376     /* Default passphrase prompter */
377     if (enc != NULL || outformat == FORMAT_PVK) {
378         OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL);
379         if (passout != NULL)
380             /* When passout given, override the passphrase prompter */
381             OSSL_ENCODER_CTX_set_passphrase(ectx,
382                                             (const unsigned char *)passout,
383                                             strlen(passout));
384     }
385
386     /* PVK is a bit special... */
387     if (outformat == FORMAT_PVK) {
388         OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
389
390         params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr);
391         if (!OSSL_ENCODER_CTX_set_params(ectx, params)) {
392             BIO_printf(bio_err, "invalid PVK encryption level\n");
393             goto end;
394         }
395     }
396
397     if (!OSSL_ENCODER_to_bio(ectx, out)) {
398         BIO_printf(bio_err, "unable to write key\n");
399         ERR_print_errors(bio_err);
400         goto end;
401     }
402     ret = 0;
403  end:
404     OSSL_ENCODER_CTX_free(ectx);
405     release_engine(e);
406     BIO_free_all(out);
407     EVP_PKEY_free(pkey);
408     EVP_CIPHER_free(enc);
409     OPENSSL_free(passin);
410     OPENSSL_free(passout);
411     return ret;
412 }