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