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