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