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