apps: silent warning when loading CSR files with vfyopt option
[openssl.git] / apps / x509.c
1 /*
2  * Copyright 1995-2022 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/bio.h>
16 #include <openssl/asn1.h>
17 #include <openssl/err.h>
18 #include <openssl/bn.h>
19 #include <openssl/evp.h>
20 #include <openssl/x509.h>
21 #include <openssl/x509v3.h>
22 #include <openssl/objects.h>
23 #include <openssl/pem.h>
24 #include <openssl/rsa.h>
25 #ifndef OPENSSL_NO_DSA
26 # include <openssl/dsa.h>
27 #endif
28
29 #undef POSTFIX
30 #define POSTFIX ".srl"
31 #define DEFAULT_DAYS    30 /* default cert validity period in days */
32 #define UNSET_DAYS      -2 /* -1 is used for testing expiration checks */
33 #define EXT_COPY_UNSET     -1
34
35 static int callb(int ok, X509_STORE_CTX *ctx);
36 static ASN1_INTEGER *x509_load_serial(const char *CAfile,
37                                       const char *serialfile, int create);
38 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
39 static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names);
40
41 typedef enum OPTION_choice {
42     OPT_COMMON,
43     OPT_INFORM, OPT_OUTFORM, OPT_KEYFORM, OPT_REQ, OPT_CAFORM,
44     OPT_CAKEYFORM, OPT_VFYOPT, OPT_SIGOPT, OPT_DAYS, OPT_PASSIN, OPT_EXTFILE,
45     OPT_EXTENSIONS, OPT_IN, OPT_OUT, OPT_KEY, OPT_SIGNKEY, OPT_CA, OPT_CAKEY,
46     OPT_CASERIAL, OPT_SET_SERIAL, OPT_NEW, OPT_FORCE_PUBKEY, OPT_SUBJ,
47     OPT_ADDTRUST, OPT_ADDREJECT, OPT_SETALIAS, OPT_CERTOPT, OPT_DATEOPT, OPT_NAMEOPT,
48     OPT_EMAIL, OPT_OCSP_URI, OPT_SERIAL, OPT_NEXT_SERIAL,
49     OPT_MODULUS, OPT_PUBKEY, OPT_X509TOREQ, OPT_TEXT, OPT_HASH,
50     OPT_ISSUER_HASH, OPT_SUBJECT, OPT_ISSUER, OPT_FINGERPRINT, OPT_DATES,
51     OPT_PURPOSE, OPT_STARTDATE, OPT_ENDDATE, OPT_CHECKEND, OPT_CHECKHOST,
52     OPT_CHECKEMAIL, OPT_CHECKIP, OPT_NOOUT, OPT_TRUSTOUT, OPT_CLRTRUST,
53     OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID,
54     OPT_SUBJECT_HASH_OLD, OPT_ISSUER_HASH_OLD, OPT_COPY_EXTENSIONS,
55     OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES,
56     OPT_R_ENUM, OPT_PROV_ENUM, OPT_EXT
57 } OPTION_CHOICE;
58
59 const OPTIONS x509_options[] = {
60     OPT_SECTION("General"),
61     {"help", OPT_HELP, '-', "Display this summary"},
62
63     {"in", OPT_IN, '<',
64      "Certificate input, or CSR input file with -req (default stdin)"},
65     {"passin", OPT_PASSIN, 's', "Private key and cert file pass-phrase source"},
66     {"new", OPT_NEW, '-', "Generate a certificate from scratch"},
67     {"x509toreq", OPT_X509TOREQ, '-',
68      "Output a certification request (rather than a certificate)"},
69     {"req", OPT_REQ, '-', "Input is a CSR file (rather than a certificate)"},
70     {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
71      "copy extensions when converting from CSR to x509 or vice versa"},
72     {"inform", OPT_INFORM, 'f',
73      "CSR input format to use (PEM or DER; by default try PEM first)"},
74     {"vfyopt", OPT_VFYOPT, 's', "CSR verification parameter in n:v form"},
75     {"key", OPT_KEY, 's',
76      "Key for signing, and to include unless using -force_pubkey"},
77     {"signkey", OPT_SIGNKEY, 's',
78      "Same as -key"},
79     {"keyform", OPT_KEYFORM, 'E',
80      "Key input format (ENGINE, other values ignored)"},
81     {"out", OPT_OUT, '>', "Output file - default stdout"},
82     {"outform", OPT_OUTFORM, 'f',
83      "Output format (DER or PEM) - default PEM"},
84     {"nocert", OPT_NOCERT, '-',
85      "No cert output (except for requested printing)"},
86     {"noout", OPT_NOOUT, '-', "No output (except for requested printing)"},
87
88     OPT_SECTION("Certificate printing"),
89     {"text", OPT_TEXT, '-', "Print the certificate in text form"},
90     {"dateopt", OPT_DATEOPT, 's',
91      "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."},
92     {"certopt", OPT_CERTOPT, 's', "Various certificate text printing options"},
93     {"fingerprint", OPT_FINGERPRINT, '-', "Print the certificate fingerprint"},
94     {"alias", OPT_ALIAS, '-', "Print certificate alias"},
95     {"serial", OPT_SERIAL, '-', "Print serial number value"},
96     {"startdate", OPT_STARTDATE, '-', "Print the notBefore field"},
97     {"enddate", OPT_ENDDATE, '-', "Print the notAfter field"},
98     {"dates", OPT_DATES, '-', "Print both notBefore and notAfter fields"},
99     {"subject", OPT_SUBJECT, '-', "Print subject DN"},
100     {"issuer", OPT_ISSUER, '-', "Print issuer DN"},
101     {"nameopt", OPT_NAMEOPT, 's',
102      "Certificate subject/issuer name printing options"},
103     {"email", OPT_EMAIL, '-', "Print email address(es)"},
104     {"hash", OPT_HASH, '-', "Synonym for -subject_hash (for backward compat)"},
105     {"subject_hash", OPT_HASH, '-', "Print subject hash value"},
106 #ifndef OPENSSL_NO_MD5
107     {"subject_hash_old", OPT_SUBJECT_HASH_OLD, '-',
108      "Print old-style (MD5) subject hash value"},
109 #endif
110     {"issuer_hash", OPT_ISSUER_HASH, '-', "Print issuer hash value"},
111 #ifndef OPENSSL_NO_MD5
112     {"issuer_hash_old", OPT_ISSUER_HASH_OLD, '-',
113      "Print old-style (MD5) issuer hash value"},
114 #endif
115     {"ext", OPT_EXT, 's',
116      "Restrict which X.509 extensions to print and/or copy"},
117     {"ocspid", OPT_OCSPID, '-',
118      "Print OCSP hash values for the subject name and public key"},
119     {"ocsp_uri", OPT_OCSP_URI, '-', "Print OCSP Responder URL(s)"},
120     {"purpose", OPT_PURPOSE, '-', "Print out certificate purposes"},
121     {"pubkey", OPT_PUBKEY, '-', "Print the public key in PEM format"},
122     {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"},
123
124     OPT_SECTION("Certificate checking"),
125     {"checkend", OPT_CHECKEND, 'M',
126      "Check whether cert expires in the next arg seconds"},
127     {OPT_MORE_STR, 1, 1, "Exit 1 (failure) if so, 0 if not"},
128     {"checkhost", OPT_CHECKHOST, 's', "Check certificate matches host"},
129     {"checkemail", OPT_CHECKEMAIL, 's', "Check certificate matches email"},
130     {"checkip", OPT_CHECKIP, 's', "Check certificate matches ipaddr"},
131
132     OPT_SECTION("Certificate output"),
133     {"set_serial", OPT_SET_SERIAL, 's',
134      "Serial number to use, overrides -CAserial"},
135     {"next_serial", OPT_NEXT_SERIAL, '-',
136      "Increment current certificate serial number"},
137     {"days", OPT_DAYS, 'n',
138      "Number of days until newly generated certificate expires - default 30"},
139     {"preserve_dates", OPT_PRESERVE_DATES, '-',
140      "Preserve existing validity dates"},
141     {"subj", OPT_SUBJ, 's', "Set or override certificate subject (and issuer)"},
142     {"force_pubkey", OPT_FORCE_PUBKEY, '<',
143      "Key to be placed in new certificate or certificate request"},
144     {"clrext", OPT_CLREXT, '-',
145      "Do not take over any extensions from the source certificate or request"},
146     {"extfile", OPT_EXTFILE, '<', "Config file with X509V3 extensions to add"},
147     {"extensions", OPT_EXTENSIONS, 's',
148      "Section of extfile to use - default: unnamed section"},
149     {"sigopt", OPT_SIGOPT, 's', "Signature parameter, in n:v form"},
150     {"badsig", OPT_BADSIG, '-',
151      "Corrupt last byte of certificate signature (for test)"},
152     {"", OPT_MD, '-', "Any supported digest, used for signing and printing"},
153
154     OPT_SECTION("Micro-CA"),
155     {"CA", OPT_CA, '<',
156      "Use the given CA certificate, conflicts with -key"},
157     {"CAform", OPT_CAFORM, 'F', "CA cert format (PEM/DER/P12); has no effect"},
158     {"CAkey", OPT_CAKEY, 's', "The corresponding CA key; default is -CA arg"},
159     {"CAkeyform", OPT_CAKEYFORM, 'E',
160      "CA key format (ENGINE, other values ignored)"},
161     {"CAserial", OPT_CASERIAL, 's',
162      "File that keeps track of CA-generated serial number"},
163     {"CAcreateserial", OPT_CACREATESERIAL, '-',
164      "Create CA serial number file if it does not exist"},
165
166     OPT_SECTION("Certificate trust output"),
167     {"trustout", OPT_TRUSTOUT, '-', "Mark certificate PEM output as trusted"},
168     {"setalias", OPT_SETALIAS, 's', "Set certificate alias (nickname)"},
169     {"clrtrust", OPT_CLRTRUST, '-', "Clear all trusted purposes"},
170     {"addtrust", OPT_ADDTRUST, 's', "Trust certificate for a given purpose"},
171     {"clrreject", OPT_CLRREJECT, '-',
172      "Clears all the prohibited or rejected uses of the certificate"},
173     {"addreject", OPT_ADDREJECT, 's',
174      "Reject certificate for a given purpose"},
175
176     OPT_R_OPTIONS,
177 #ifndef OPENSSL_NO_ENGINE
178     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
179 #endif
180     OPT_PROV_OPTIONS,
181     {NULL}
182 };
183
184 static void warn_copying(ASN1_OBJECT *excluded, const char *names)
185 {
186     const char *sn = OBJ_nid2sn(OBJ_obj2nid(excluded));
187
188     if (names != NULL && strstr(names, sn) != NULL)
189         BIO_printf(bio_err,
190                    "Warning: -ext should not specify copying %s extension to CSR; ignoring this\n",
191                    sn);
192 }
193
194 static X509_REQ *x509_to_req(X509 *cert, int ext_copy, const char *names)
195 {
196     const STACK_OF(X509_EXTENSION) *cert_exts = X509_get0_extensions(cert);
197     int i, n = sk_X509_EXTENSION_num(cert_exts /* may be NULL */);
198     ASN1_OBJECT *skid = OBJ_nid2obj(NID_subject_key_identifier);
199     ASN1_OBJECT *akid = OBJ_nid2obj(NID_authority_key_identifier);
200     STACK_OF(X509_EXTENSION) *exts;
201     X509_REQ *req = X509_to_X509_REQ(cert, NULL, NULL);
202
203     if (req == NULL)
204         return NULL;
205
206     /*
207      * Filter out SKID and AKID extensions, which make no sense in a CSR.
208      * If names is not NULL, copy only those extensions listed there.
209      */
210     warn_copying(skid, names);
211     warn_copying(akid, names);
212     if ((exts = sk_X509_EXTENSION_new_reserve(NULL, n)) == NULL)
213         goto err;
214     for (i = 0; i < n; i++) {
215         X509_EXTENSION *ex = sk_X509_EXTENSION_value(cert_exts, i);
216         ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex);
217
218         if (OBJ_cmp(obj, skid) != 0 && OBJ_cmp(obj, akid) != 0
219                 && !sk_X509_EXTENSION_push(exts, ex))
220             goto err;
221     }
222
223     if (sk_X509_EXTENSION_num(exts) > 0) {
224         if (ext_copy != EXT_COPY_UNSET && ext_copy != EXT_COPY_NONE
225                 && !X509_REQ_add_extensions(req, exts)) {
226             BIO_printf(bio_err, "Error copying extensions from certificate\n");
227             goto err;
228         }
229     }
230     sk_X509_EXTENSION_free(exts);
231     return req;
232
233  err:
234     sk_X509_EXTENSION_free(exts);
235     X509_REQ_free(req);
236     return NULL;
237 }
238
239 static int self_signed(X509_STORE *ctx, X509 *cert)
240 {
241     X509_STORE_CTX *xsc = X509_STORE_CTX_new();
242     int ret = 0;
243
244     if (xsc == NULL || !X509_STORE_CTX_init(xsc, ctx, cert, NULL)) {
245         BIO_printf(bio_err, "Error initialising X509 store\n");
246     } else {
247         X509_STORE_CTX_set_flags(xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
248         ret = X509_verify_cert(xsc) > 0;
249     }
250     X509_STORE_CTX_free(xsc);
251     return ret;
252 }
253
254 int x509_main(int argc, char **argv)
255 {
256     ASN1_INTEGER *sno = NULL;
257     ASN1_OBJECT *objtmp = NULL;
258     BIO *out = NULL;
259     CONF *extconf = NULL;
260     int ext_copy = EXT_COPY_UNSET;
261     X509V3_CTX ext_ctx;
262     EVP_PKEY *privkey = NULL, *CAkey = NULL, *pubkey = NULL;
263     EVP_PKEY *pkey;
264     int newcert = 0;
265     char *subj = NULL, *digest = NULL;
266     X509_NAME *fsubj = NULL;
267     const unsigned long chtype = MBSTRING_ASC;
268     const int multirdn = 1;
269     STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
270     STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL;
271     X509 *x = NULL, *xca = NULL, *issuer_cert;
272     X509_REQ *req = NULL, *rq = NULL;
273     X509_STORE *ctx = NULL;
274     char *CAkeyfile = NULL, *CAserial = NULL, *pubkeyfile = NULL, *alias = NULL;
275     char *checkhost = NULL, *checkemail = NULL, *checkip = NULL;
276     char *ext_names = NULL;
277     char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL;
278     char *infile = NULL, *outfile = NULL, *privkeyfile = NULL, *CAfile = NULL;
279     char *prog;
280     int days = UNSET_DAYS; /* not explicitly set */
281     int x509toreq = 0, modulus = 0, print_pubkey = 0, pprint = 0;
282     int CAformat = FORMAT_UNDEF, CAkeyformat = FORMAT_UNDEF;
283     unsigned long dateopt = ASN1_DTFLGS_RFC822;
284     int fingerprint = 0, reqfile = 0, checkend = 0;
285     int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF;
286     int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0;
287     int noout = 0, CA_createserial = 0, email = 0;
288     int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0;
289     int ret = 1, i, j, num = 0, badsig = 0, clrext = 0, nocert = 0;
290     int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0;
291     int enddate = 0;
292     time_t checkoffset = 0;
293     unsigned long certflag = 0;
294     int preserve_dates = 0;
295     OPTION_CHOICE o;
296     ENGINE *e = NULL;
297 #ifndef OPENSSL_NO_MD5
298     int subject_hash_old = 0, issuer_hash_old = 0;
299 #endif
300
301     ctx = X509_STORE_new();
302     if (ctx == NULL)
303         goto err;
304     X509_STORE_set_verify_cb(ctx, callb);
305
306     opt_set_unknown_name("digest");
307     prog = opt_init(argc, argv, x509_options);
308     while ((o = opt_next()) != OPT_EOF) {
309         switch (o) {
310         case OPT_EOF:
311         case OPT_ERR:
312  opthelp:
313             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
314             goto err;
315         case OPT_HELP:
316             opt_help(x509_options);
317             ret = 0;
318             goto end;
319         case OPT_INFORM:
320             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
321                 goto opthelp;
322             break;
323         case OPT_IN:
324             infile = opt_arg();
325             break;
326         case OPT_OUTFORM:
327             if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
328                 goto opthelp;
329             break;
330         case OPT_KEYFORM:
331             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
332                 goto opthelp;
333             break;
334         case OPT_CAFORM:
335             if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAformat))
336                 goto opthelp;
337             break;
338         case OPT_CAKEYFORM:
339             if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAkeyformat))
340                 goto opthelp;
341             break;
342         case OPT_OUT:
343             outfile = opt_arg();
344             break;
345         case OPT_REQ:
346             reqfile = 1;
347             break;
348
349         case OPT_DATEOPT:
350             if (!set_dateopt(&dateopt, opt_arg())) {
351                 BIO_printf(bio_err,
352                            "Invalid date format: %s\n", opt_arg());
353                 goto err;
354             }
355             break;
356         case OPT_COPY_EXTENSIONS:
357             if (!set_ext_copy(&ext_copy, opt_arg())) {
358                 BIO_printf(bio_err,
359                            "Invalid extension copy option: %s\n", opt_arg());
360                 goto err;
361             }
362             break;
363
364         case OPT_SIGOPT:
365             if (!sigopts)
366                 sigopts = sk_OPENSSL_STRING_new_null();
367             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
368                 goto opthelp;
369             break;
370         case OPT_VFYOPT:
371             if (!vfyopts)
372                 vfyopts = sk_OPENSSL_STRING_new_null();
373             if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
374                 goto opthelp;
375             break;
376         case OPT_DAYS:
377             days = atoi(opt_arg());
378             if (days < -1) {
379                 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
380                            prog);
381                 goto err;
382             }
383             break;
384         case OPT_PASSIN:
385             passinarg = opt_arg();
386             break;
387         case OPT_EXTFILE:
388             extfile = opt_arg();
389             break;
390         case OPT_R_CASES:
391             if (!opt_rand(o))
392                 goto end;
393             break;
394         case OPT_PROV_CASES:
395             if (!opt_provider(o))
396                 goto end;
397             break;
398         case OPT_EXTENSIONS:
399             extsect = opt_arg();
400             break;
401         case OPT_KEY:
402         case OPT_SIGNKEY:
403             privkeyfile = opt_arg();
404             break;
405         case OPT_CA:
406             CAfile = opt_arg();
407             break;
408         case OPT_CAKEY:
409             CAkeyfile = opt_arg();
410             break;
411         case OPT_CASERIAL:
412             CAserial = opt_arg();
413             break;
414         case OPT_SET_SERIAL:
415             if (sno != NULL) {
416                 BIO_printf(bio_err, "Serial number supplied twice\n");
417                 goto opthelp;
418             }
419             if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL)
420                 goto opthelp;
421             break;
422         case OPT_NEW:
423             newcert = 1;
424             break;
425         case OPT_FORCE_PUBKEY:
426             pubkeyfile = opt_arg();
427             break;
428         case OPT_SUBJ:
429             subj = opt_arg();
430             break;
431         case OPT_ADDTRUST:
432             if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL)
433                 goto end;
434             if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
435                 BIO_printf(bio_err, "%s: Invalid trust object value %s\n",
436                            prog, opt_arg());
437                 goto opthelp;
438             }
439             sk_ASN1_OBJECT_push(trust, objtmp);
440             trustout = 1;
441             break;
442         case OPT_ADDREJECT:
443             if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL)
444                 goto end;
445             if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
446                 BIO_printf(bio_err, "%s: Invalid reject object value %s\n",
447                            prog, opt_arg());
448                 goto opthelp;
449             }
450             sk_ASN1_OBJECT_push(reject, objtmp);
451             trustout = 1;
452             break;
453         case OPT_SETALIAS:
454             alias = opt_arg();
455             trustout = 1;
456             break;
457         case OPT_CERTOPT:
458             if (!set_cert_ex(&certflag, opt_arg()))
459                 goto opthelp;
460             break;
461         case OPT_NAMEOPT:
462             if (!set_nameopt(opt_arg()))
463                 goto opthelp;
464             break;
465         case OPT_ENGINE:
466             e = setup_engine(opt_arg(), 0);
467             break;
468         case OPT_EMAIL:
469             email = ++num;
470             break;
471         case OPT_OCSP_URI:
472             ocsp_uri = ++num;
473             break;
474         case OPT_SERIAL:
475             serial = ++num;
476             break;
477         case OPT_NEXT_SERIAL:
478             next_serial = ++num;
479             break;
480         case OPT_MODULUS:
481             modulus = ++num;
482             break;
483         case OPT_PUBKEY:
484             print_pubkey = ++num;
485             break;
486         case OPT_X509TOREQ:
487             x509toreq = 1;
488             break;
489         case OPT_TEXT:
490             text = ++num;
491             break;
492         case OPT_SUBJECT:
493             subject = ++num;
494             break;
495         case OPT_ISSUER:
496             issuer = ++num;
497             break;
498         case OPT_FINGERPRINT:
499             fingerprint = ++num;
500             break;
501         case OPT_HASH:
502             subject_hash = ++num;
503             break;
504         case OPT_ISSUER_HASH:
505             issuer_hash = ++num;
506             break;
507         case OPT_PURPOSE:
508             pprint = ++num;
509             break;
510         case OPT_STARTDATE:
511             startdate = ++num;
512             break;
513         case OPT_ENDDATE:
514             enddate = ++num;
515             break;
516         case OPT_NOOUT:
517             noout = ++num;
518             break;
519         case OPT_EXT:
520             ext = ++num;
521             ext_names = opt_arg();
522             break;
523         case OPT_NOCERT:
524             nocert = 1;
525             break;
526         case OPT_TRUSTOUT:
527             trustout = 1;
528             break;
529         case OPT_CLRTRUST:
530             clrtrust = ++num;
531             break;
532         case OPT_CLRREJECT:
533             clrreject = ++num;
534             break;
535         case OPT_ALIAS:
536             aliasout = ++num;
537             break;
538         case OPT_CACREATESERIAL:
539             CA_createserial = 1;
540             break;
541         case OPT_CLREXT:
542             clrext = 1;
543             break;
544         case OPT_OCSPID:
545             ocspid = ++num;
546             break;
547         case OPT_BADSIG:
548             badsig = 1;
549             break;
550 #ifndef OPENSSL_NO_MD5
551         case OPT_SUBJECT_HASH_OLD:
552             subject_hash_old = ++num;
553             break;
554         case OPT_ISSUER_HASH_OLD:
555             issuer_hash_old = ++num;
556             break;
557 #else
558         case OPT_SUBJECT_HASH_OLD:
559         case OPT_ISSUER_HASH_OLD:
560             break;
561 #endif
562         case OPT_DATES:
563             startdate = ++num;
564             enddate = ++num;
565             break;
566         case OPT_CHECKEND:
567             checkend = 1;
568             {
569                 ossl_intmax_t temp = 0;
570                 if (!opt_intmax(opt_arg(), &temp))
571                     goto opthelp;
572                 checkoffset = (time_t)temp;
573                 if ((ossl_intmax_t)checkoffset != temp) {
574                     BIO_printf(bio_err, "%s: Checkend time out of range %s\n",
575                                prog, opt_arg());
576                     goto opthelp;
577                 }
578             }
579             break;
580         case OPT_CHECKHOST:
581             checkhost = opt_arg();
582             break;
583         case OPT_CHECKEMAIL:
584             checkemail = opt_arg();
585             break;
586         case OPT_CHECKIP:
587             checkip = opt_arg();
588             break;
589         case OPT_PRESERVE_DATES:
590             preserve_dates = 1;
591             break;
592         case OPT_MD:
593             digest = opt_unknown();
594             break;
595         }
596     }
597     /* No extra arguments. */
598     if (!opt_check_rest_arg(NULL))
599         goto opthelp;
600
601     if (!app_RAND_load())
602         goto end;
603
604     if (!opt_check_md(digest))
605         goto opthelp;
606
607     if (preserve_dates && days != UNSET_DAYS) {
608         BIO_printf(bio_err, "Cannot use -preserve_dates with -days option\n");
609         goto err;
610     }
611     if (days == UNSET_DAYS)
612         days = DEFAULT_DAYS;
613
614     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
615         BIO_printf(bio_err, "Error getting password\n");
616         goto err;
617     }
618
619     if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(),
620                                          app_get0_propq()))
621         goto end;
622
623     if (newcert && infile != NULL) {
624         BIO_printf(bio_err, "The -in option cannot be used with -new\n");
625         goto err;
626     }
627     if (newcert && reqfile) {
628         BIO_printf(bio_err, "The -req option cannot be used with -new\n");
629         goto err;
630     }
631     if (privkeyfile != NULL) {
632         privkey = load_key(privkeyfile, keyformat, 0, passin, e, "private key");
633         if (privkey == NULL)
634             goto end;
635     }
636     if (pubkeyfile != NULL) {
637         if ((pubkey = load_pubkey(pubkeyfile, keyformat, 0, NULL, e,
638                                   "explicitly set public key")) == NULL)
639             goto end;
640     }
641
642     if (newcert) {
643         if (subj == NULL) {
644             BIO_printf(bio_err,
645                        "The -new option requires a subject to be set using -subj\n");
646             goto err;
647         }
648         if (privkeyfile == NULL && pubkeyfile == NULL) {
649             BIO_printf(bio_err,
650                        "The -new option requires using the -key or -force_pubkey option\n");
651             goto err;
652         }
653     }
654     if (subj != NULL
655             && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
656         goto end;
657
658     if (CAkeyfile == NULL)
659         CAkeyfile = CAfile;
660     if (CAfile != NULL) {
661         if (privkeyfile != NULL) {
662             BIO_printf(bio_err, "Cannot use both -key/-signkey and -CA option\n");
663             goto err;
664         }
665     } else {
666 #define WARN_NO_CA(opt) BIO_printf(bio_err, \
667         "Warning: ignoring " opt " option since -CA option is not given\n");
668         if (CAkeyfile != NULL)
669             WARN_NO_CA("-CAkey");
670         if (CAkeyformat != FORMAT_UNDEF)
671             WARN_NO_CA("-CAkeyform");
672         if (CAformat != FORMAT_UNDEF)
673             WARN_NO_CA("-CAform");
674         if (CAserial != NULL)
675             WARN_NO_CA("-CAserial");
676         if (CA_createserial)
677             WARN_NO_CA("-CAcreateserial");
678     }
679
680     if (extfile == NULL) {
681         if (extsect != NULL)
682             BIO_printf(bio_err,
683                        "Warning: ignoring -extensions option without -extfile\n");
684     } else {
685         X509V3_CTX ctx2;
686
687         if ((extconf = app_load_config(extfile)) == NULL)
688             goto end;
689         if (extsect == NULL) {
690             extsect = NCONF_get_string(extconf, "default", "extensions");
691             if (extsect == NULL) {
692                 ERR_clear_error();
693                 extsect = "default";
694             }
695         }
696         X509V3_set_ctx_test(&ctx2);
697         X509V3_set_nconf(&ctx2, extconf);
698         if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
699             BIO_printf(bio_err,
700                        "Error checking extension section %s\n", extsect);
701             goto err;
702         }
703     }
704
705     if (reqfile) {
706         if (infile == NULL)
707             BIO_printf(bio_err,
708                        "Warning: Reading cert request from stdin since no -in option is given\n");
709         req = load_csr_autofmt(infile, informat, vfyopts,
710                                "certificate request input");
711         if (req == NULL)
712             goto end;
713
714         if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) {
715             BIO_printf(bio_err, "Error unpacking public key from CSR\n");
716             goto err;
717         }
718         i = do_X509_REQ_verify(req, pkey, vfyopts);
719         if (i <= 0) {
720             BIO_printf(bio_err, i < 0
721                        ? "Error while verifying certificate request self-signature\n"
722                        : "Certificate request self-signature did not match the contents\n");
723             goto err;
724         }
725         BIO_printf(bio_err, "Certificate request self-signature ok\n");
726
727         print_name(bio_err, "subject=", X509_REQ_get_subject_name(req));
728     } else if (!x509toreq && ext_copy != EXT_COPY_UNSET) {
729         BIO_printf(bio_err, "Warning: ignoring -copy_extensions since neither -x509toreq nor -req is given\n");
730     }
731
732     if (reqfile || newcert) {
733         if (preserve_dates)
734             BIO_printf(bio_err,
735                        "Warning: ignoring -preserve_dates option with -req or -new\n");
736         preserve_dates = 0;
737         if (privkeyfile == NULL && CAkeyfile == NULL) {
738             BIO_printf(bio_err,
739                        "We need a private key to sign with, use -key or -CAkey or -CA with private key\n");
740             goto err;
741         }
742         if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
743             goto end;
744         if (CAfile == NULL && sno == NULL) {
745             sno = ASN1_INTEGER_new();
746             if (sno == NULL || !rand_serial(NULL, sno))
747                 goto end;
748         }
749         if (req != NULL && ext_copy != EXT_COPY_UNSET) {
750             if (clrext && ext_copy != EXT_COPY_NONE) {
751                 BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
752                 goto err;
753             } else if (!copy_extensions(x, req, ext_copy)) {
754                 BIO_printf(bio_err, "Error copying extensions from request\n");
755                 goto err;
756             }
757         }
758     } else {
759         if (infile == NULL)
760             BIO_printf(bio_err,
761                        "Warning: Reading certificate from stdin since no -in or -new option is given\n");
762         x = load_cert_pass(infile, informat, 1, passin, "certificate");
763         if (x == NULL)
764             goto end;
765     }
766     if ((fsubj != NULL || req != NULL)
767         && !X509_set_subject_name(x, fsubj != NULL ? fsubj :
768                                   X509_REQ_get_subject_name(req)))
769         goto end;
770     if ((pubkey != NULL || privkey != NULL || req != NULL)
771         && !X509_set_pubkey(x, pubkey != NULL ? pubkey :
772                             privkey != NULL ? privkey :
773                             X509_REQ_get0_pubkey(req)))
774         goto end;
775
776     if (CAfile != NULL) {
777         xca = load_cert_pass(CAfile, CAformat, 1, passin, "CA certificate");
778         if (xca == NULL)
779             goto end;
780     }
781
782     out = bio_open_default(outfile, 'w', outformat);
783     if (out == NULL)
784         goto end;
785
786     if (alias)
787         X509_alias_set1(x, (unsigned char *)alias, -1);
788
789     if (clrtrust)
790         X509_trust_clear(x);
791     if (clrreject)
792         X509_reject_clear(x);
793
794     if (trust != NULL) {
795         for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++)
796             X509_add1_trust_object(x, sk_ASN1_OBJECT_value(trust, i));
797     }
798
799     if (reject != NULL) {
800         for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++)
801             X509_add1_reject_object(x, sk_ASN1_OBJECT_value(reject, i));
802     }
803
804     if (clrext && ext_names != NULL)
805         BIO_printf(bio_err, "Warning: Ignoring -ext since -clrext is given\n");
806     for (i = X509_get_ext_count(x) - 1; i >= 0; i--) {
807         X509_EXTENSION *ex = X509_get_ext(x, i);
808         const char *sn = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ex)));
809
810         if (clrext || (ext_names != NULL && strstr(ext_names, sn) == NULL))
811             X509_EXTENSION_free(X509_delete_ext(x, i));
812     }
813
814     issuer_cert = x;
815     if (CAfile != NULL) {
816         issuer_cert = xca;
817         if (sno == NULL)
818             sno = x509_load_serial(CAfile, CAserial, CA_createserial);
819         if (sno == NULL)
820             goto end;
821         if (!x509toreq && !reqfile && !newcert && !self_signed(ctx, x))
822             goto end;
823     } else {
824         if (privkey != NULL && !cert_matches_key(x, privkey))
825             BIO_printf(bio_err,
826                        "Warning: Signature key and public key of cert do not match\n");
827     }
828
829     if (sno != NULL && !X509_set_serialNumber(x, sno))
830         goto end;
831
832     if (reqfile || newcert || privkey != NULL || CAfile != NULL) {
833         if (!preserve_dates && !set_cert_times(x, NULL, NULL, days))
834             goto end;
835         if (!X509_set_issuer_name(x, X509_get_subject_name(issuer_cert)))
836             goto end;
837     }
838
839     X509V3_set_ctx(&ext_ctx, issuer_cert, x, NULL, NULL, X509V3_CTX_REPLACE);
840     /* prepare fallback for AKID, but only if issuer cert equals subject cert */
841     if (CAfile == NULL) {
842         if (!X509V3_set_issuer_pkey(&ext_ctx, privkey))
843             goto end;
844     }
845     if (extconf != NULL && !x509toreq) {
846         X509V3_set_nconf(&ext_ctx, extconf);
847         if (!X509V3_EXT_add_nconf(extconf, &ext_ctx, extsect, x)) {
848             BIO_printf(bio_err,
849                        "Error adding extensions from section %s\n", extsect);
850             goto err;
851         }
852     }
853
854     /* At this point the contents of the certificate x have been finished. */
855
856     pkey = X509_get0_pubkey(x);
857     if ((print_pubkey != 0 || modulus != 0) && pkey == NULL) {
858         BIO_printf(bio_err, "Error getting public key\n");
859         goto err;
860     }
861
862     if (x509toreq) { /* also works in conjunction with -req */
863         if (privkey == NULL) {
864             BIO_printf(bio_err, "Must specify request signing key using -key\n");
865             goto err;
866         }
867         if (clrext && ext_copy != EXT_COPY_NONE) {
868             BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
869             goto err;
870         }
871         if ((rq = x509_to_req(x, ext_copy, ext_names)) == NULL)
872             goto end;
873         if (extconf != NULL) {
874             X509V3_set_nconf(&ext_ctx, extconf);
875             if (!X509V3_EXT_REQ_add_nconf(extconf, &ext_ctx, extsect, rq)) {
876                 BIO_printf(bio_err,
877                            "Error adding request extensions from section %s\n", extsect);
878                 goto err;
879             }
880         }
881         if (!do_X509_REQ_sign(rq, privkey, digest, sigopts))
882             goto end;
883         if (!noout) {
884             if (outformat == FORMAT_ASN1) {
885                 X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT);
886                 i = i2d_X509_bio(out, x);
887             } else {
888                 i = PEM_write_bio_X509_REQ(out, rq);
889             }
890             if (!i) {
891                 BIO_printf(bio_err,
892                            "Unable to write certificate request\n");
893                 goto err;
894             }
895         }
896         noout = 1;
897     } else if (CAfile != NULL) {
898         if ((CAkey = load_key(CAkeyfile, CAkeyformat,
899                               0, passin, e, "CA private key")) == NULL)
900             goto end;
901         if (!X509_check_private_key(xca, CAkey)) {
902             BIO_printf(bio_err,
903                        "CA certificate and CA private key do not match\n");
904             goto err;
905         }
906
907         if (!do_X509_sign(x, 0, CAkey, digest, sigopts, &ext_ctx))
908             goto end;
909     } else if (privkey != NULL) {
910         if (!do_X509_sign(x, 0, privkey, digest, sigopts, &ext_ctx))
911             goto end;
912     }
913     if (badsig) {
914         const ASN1_BIT_STRING *signature;
915
916         X509_get0_signature(&signature, NULL, x);
917         corrupt_signature(signature);
918     }
919
920     /* Process print options in the given order, as indicated by index i */
921     for (i = 1; i <= num; i++) {
922         if (i == issuer) {
923             print_name(out, "issuer=", X509_get_issuer_name(x));
924         } else if (i == subject) {
925             print_name(out, "subject=", X509_get_subject_name(x));
926         } else if (i == serial) {
927             BIO_printf(out, "serial=");
928             i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x));
929             BIO_printf(out, "\n");
930         } else if (i == next_serial) {
931             ASN1_INTEGER *ser;
932             BIGNUM *bnser = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x), NULL);
933
934             if (bnser == NULL)
935                 goto end;
936             if (!BN_add_word(bnser, 1)
937                     || (ser = BN_to_ASN1_INTEGER(bnser, NULL)) == NULL) {
938                 BN_free(bnser);
939                 goto end;
940             }
941             BN_free(bnser);
942             i2a_ASN1_INTEGER(out, ser);
943             ASN1_INTEGER_free(ser);
944             BIO_puts(out, "\n");
945         } else if (i == email || i == ocsp_uri) {
946             STACK_OF(OPENSSL_STRING) *emlst =
947                 i == email ? X509_get1_email(x) : X509_get1_ocsp(x);
948
949             for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
950                 BIO_printf(out, "%s\n", sk_OPENSSL_STRING_value(emlst, j));
951             X509_email_free(emlst);
952         } else if (i == aliasout) {
953             unsigned char *alstr = X509_alias_get0(x, NULL);
954
955             if (alstr)
956                 BIO_printf(out, "%s\n", alstr);
957             else
958                 BIO_puts(out, "<No Alias>\n");
959         } else if (i == subject_hash) {
960             BIO_printf(out, "%08lx\n", X509_subject_name_hash(x));
961 #ifndef OPENSSL_NO_MD5
962         } else if (i == subject_hash_old) {
963             BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x));
964 #endif
965         } else if (i == issuer_hash) {
966             BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x));
967 #ifndef OPENSSL_NO_MD5
968         } else if (i == issuer_hash_old) {
969             BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x));
970 #endif
971         } else if (i == pprint) {
972             BIO_printf(out, "Certificate purposes:\n");
973             for (j = 0; j < X509_PURPOSE_get_count(); j++)
974                 purpose_print(out, x, X509_PURPOSE_get0(j));
975         } else if (i == modulus) {
976             BIO_printf(out, "Modulus=");
977             if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) {
978                 BIGNUM *n = NULL;
979
980                 /* Every RSA key has an 'n' */
981                 EVP_PKEY_get_bn_param(pkey, "n", &n);
982                 BN_print(out, n);
983                 BN_free(n);
984             } else if (EVP_PKEY_is_a(pkey, "DSA")) {
985                 BIGNUM *dsapub = NULL;
986
987                 /* Every DSA key has a 'pub' */
988                 EVP_PKEY_get_bn_param(pkey, "pub", &dsapub);
989                 BN_print(out, dsapub);
990                 BN_free(dsapub);
991             } else {
992                 BIO_printf(out, "No modulus for this public key type");
993             }
994             BIO_printf(out, "\n");
995         } else if (i == print_pubkey) {
996             PEM_write_bio_PUBKEY(out, pkey);
997         } else if (i == text) {
998             X509_print_ex(out, x, get_nameopt(), certflag);
999         } else if (i == startdate) {
1000             BIO_puts(out, "notBefore=");
1001             ASN1_TIME_print_ex(out, X509_get0_notBefore(x), dateopt);
1002             BIO_puts(out, "\n");
1003         } else if (i == enddate) {
1004             BIO_puts(out, "notAfter=");
1005             ASN1_TIME_print_ex(out, X509_get0_notAfter(x), dateopt);
1006             BIO_puts(out, "\n");
1007         } else if (i == fingerprint) {
1008             unsigned int n;
1009             unsigned char md[EVP_MAX_MD_SIZE];
1010             const char *fdigname = digest;
1011             EVP_MD *fdig;
1012             int digres;
1013
1014             if (fdigname == NULL)
1015                 fdigname = "SHA1";
1016
1017             if ((fdig = EVP_MD_fetch(app_get0_libctx(), fdigname,
1018                                      app_get0_propq())) == NULL) {
1019                 BIO_printf(bio_err, "Unknown digest\n");
1020                 goto err;
1021             }
1022             digres = X509_digest(x, fdig, md, &n);
1023             EVP_MD_free(fdig);
1024             if (!digres) {
1025                 BIO_printf(bio_err, "Out of memory\n");
1026                 goto err;
1027             }
1028
1029             BIO_printf(out, "%s Fingerprint=", fdigname);
1030             for (j = 0; j < (int)n; j++)
1031                 BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':');
1032         } else if (i == ocspid) {
1033             X509_ocspid_print(out, x);
1034         } else if (i == ext) {
1035             print_x509v3_exts(out, x, ext_names);
1036         }
1037     }
1038
1039     if (checkend) {
1040         time_t tcheck = time(NULL) + checkoffset;
1041
1042         ret = X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0;
1043         if (ret)
1044             BIO_printf(out, "Certificate will expire\n");
1045         else
1046             BIO_printf(out, "Certificate will not expire\n");
1047         goto end;
1048     }
1049
1050     if (!check_cert_attributes(out, x, checkhost, checkemail, checkip, 1))
1051         goto err;
1052
1053     if (noout || nocert) {
1054         ret = 0;
1055         goto end;
1056     }
1057
1058     if (outformat == FORMAT_ASN1) {
1059         i = i2d_X509_bio(out, x);
1060     } else if (outformat == FORMAT_PEM) {
1061         if (trustout)
1062             i = PEM_write_bio_X509_AUX(out, x);
1063         else
1064             i = PEM_write_bio_X509(out, x);
1065     } else {
1066         BIO_printf(bio_err, "Bad output format specified for outfile\n");
1067         goto err;
1068     }
1069     if (!i) {
1070         BIO_printf(bio_err, "Unable to write certificate\n");
1071         goto err;
1072     }
1073
1074     ret = 0;
1075     goto end;
1076
1077  err:
1078     ERR_print_errors(bio_err);
1079
1080  end:
1081     NCONF_free(extconf);
1082     BIO_free_all(out);
1083     X509_STORE_free(ctx);
1084     X509_NAME_free(fsubj);
1085     X509_REQ_free(req);
1086     X509_free(x);
1087     X509_free(xca);
1088     EVP_PKEY_free(privkey);
1089     EVP_PKEY_free(CAkey);
1090     EVP_PKEY_free(pubkey);
1091     sk_OPENSSL_STRING_free(sigopts);
1092     sk_OPENSSL_STRING_free(vfyopts);
1093     X509_REQ_free(rq);
1094     ASN1_INTEGER_free(sno);
1095     sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
1096     sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
1097     release_engine(e);
1098     clear_free(passin);
1099     return ret;
1100 }
1101
1102 static ASN1_INTEGER *x509_load_serial(const char *CAfile,
1103                                       const char *serialfile, int create)
1104 {
1105     char *buf = NULL;
1106     ASN1_INTEGER *bs = NULL;
1107     BIGNUM *serial = NULL;
1108     int defaultfile = 0, file_exists;
1109
1110     if (serialfile == NULL) {
1111         const char *p = strrchr(CAfile, '.');
1112         size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile);
1113
1114         buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer");
1115         memcpy(buf, CAfile, len);
1116         memcpy(buf + len, POSTFIX, sizeof(POSTFIX));
1117         serialfile = buf;
1118         defaultfile = 1;
1119     }
1120
1121     serial = load_serial(serialfile, &file_exists, create || defaultfile, NULL);
1122     if (serial == NULL)
1123         goto end;
1124
1125     if (!BN_add_word(serial, 1)) {
1126         BIO_printf(bio_err, "Serial number increment failure\n");
1127         goto end;
1128     }
1129
1130     if (file_exists || create)
1131         save_serial(serialfile, NULL, serial, &bs);
1132     else
1133         bs = BN_to_ASN1_INTEGER(serial, NULL);
1134
1135  end:
1136     OPENSSL_free(buf);
1137     BN_free(serial);
1138     return bs;
1139 }
1140
1141 static int callb(int ok, X509_STORE_CTX *ctx)
1142 {
1143     int err;
1144     X509 *err_cert;
1145
1146     /*
1147      * It is ok to use a self-signed certificate. This case will catch both
1148      * the initial ok == 0 and the final ok == 1 calls to this function.
1149      */
1150     err = X509_STORE_CTX_get_error(ctx);
1151     if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1152         return 1;
1153
1154     /*
1155      * BAD we should have gotten an error.  Normally if everything worked
1156      * X509_STORE_CTX_get_error(ctx) will still be set to
1157      * DEPTH_ZERO_SELF_....
1158      */
1159     if (ok) {
1160         BIO_printf(bio_err,
1161                    "Error with certificate to be certified - should be self-signed\n");
1162         return 0;
1163     } else {
1164         err_cert = X509_STORE_CTX_get_current_cert(ctx);
1165         print_name(bio_err, "subject=", X509_get_subject_name(err_cert));
1166         BIO_printf(bio_err,
1167                    "Error with certificate - error %d at depth %d\n%s\n", err,
1168                    X509_STORE_CTX_get_error_depth(ctx),
1169                    X509_verify_cert_error_string(err));
1170         return 1;
1171     }
1172 }
1173
1174 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1175 {
1176     int id, i, idret;
1177     const char *pname;
1178     id = X509_PURPOSE_get_id(pt);
1179     pname = X509_PURPOSE_get0_name(pt);
1180     for (i = 0; i < 2; i++) {
1181         idret = X509_check_purpose(cert, id, i);
1182         BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
1183         if (idret == 1)
1184             BIO_printf(bio, "Yes\n");
1185         else if (idret == 0)
1186             BIO_printf(bio, "No\n");
1187         else
1188             BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1189     }
1190     return 1;
1191 }
1192
1193 static int parse_ext_names(char *names, const char **result)
1194 {
1195     char *p, *q;
1196     int cnt = 0, len = 0;
1197
1198     p = q = names;
1199     len = strlen(names);
1200
1201     while (q - names <= len) {
1202         if (*q != ',' && *q != '\0') {
1203             q++;
1204             continue;
1205         }
1206         if (p != q) {
1207             /* found */
1208             if (result != NULL) {
1209                 result[cnt] = p;
1210                 *q = '\0';
1211             }
1212             cnt++;
1213         }
1214         p = ++q;
1215     }
1216
1217     return cnt;
1218 }
1219
1220 static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names)
1221 {
1222     const STACK_OF(X509_EXTENSION) *exts = NULL;
1223     STACK_OF(X509_EXTENSION) *exts2 = NULL;
1224     X509_EXTENSION *ext = NULL;
1225     ASN1_OBJECT *obj;
1226     int i, j, ret = 0, num, nn = 0;
1227     const char *sn, **names = NULL;
1228     char *tmp_ext_names = NULL;
1229
1230     exts = X509_get0_extensions(x);
1231     if ((num = sk_X509_EXTENSION_num(exts)) <= 0) {
1232         BIO_printf(bio_err, "No extensions in certificate\n");
1233         ret = 1;
1234         goto end;
1235     }
1236
1237     /* parse comma separated ext name string */
1238     if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL)
1239         goto end;
1240     if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) {
1241         BIO_printf(bio, "Invalid extension names: %s\n", ext_names);
1242         goto end;
1243     }
1244     if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL)
1245         goto end;
1246     parse_ext_names(tmp_ext_names, names);
1247
1248     for (i = 0; i < num; i++) {
1249         ext = sk_X509_EXTENSION_value(exts, i);
1250
1251         /* check if this ext is what we want */
1252         obj = X509_EXTENSION_get_object(ext);
1253         sn = OBJ_nid2sn(OBJ_obj2nid(obj));
1254         if (sn == NULL || strcmp(sn, "UNDEF") == 0)
1255             continue;
1256
1257         for (j = 0; j < nn; j++) {
1258             if (strcmp(sn, names[j]) == 0) {
1259                 /* push the extension into a new stack */
1260                 if (exts2 == NULL
1261                     && (exts2 = sk_X509_EXTENSION_new_null()) == NULL)
1262                     goto end;
1263                 if (!sk_X509_EXTENSION_push(exts2, ext))
1264                     goto end;
1265             }
1266         }
1267     }
1268
1269     if (!sk_X509_EXTENSION_num(exts2)) {
1270         BIO_printf(bio, "No extensions matched with %s\n", ext_names);
1271         ret = 1;
1272         goto end;
1273     }
1274
1275     ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0);
1276  end:
1277     sk_X509_EXTENSION_free(exts2);
1278     OPENSSL_free(names);
1279     OPENSSL_free(tmp_ext_names);
1280     return ret;
1281 }