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