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