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