xref: /freebsd/crypto/openssl/apps/x509.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*
2  * Copyright 1995-2025 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 
warn_copying(ASN1_OBJECT * excluded,const char * names)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 
x509_to_req(X509 * cert,int ext_copy,const char * names)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 
self_signed(X509_STORE * ctx,X509 * cert)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 
x509_main(int argc,char ** argv)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 err;
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             if (!sk_ASN1_OBJECT_push(trust, objtmp))
457                 goto err;
458             trustout = 1;
459             break;
460         case OPT_ADDREJECT:
461             if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL)
462                 goto err;
463             if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
464                 BIO_printf(bio_err, "%s: Invalid reject object value %s\n",
465                            prog, opt_arg());
466                 goto opthelp;
467             }
468             if (!sk_ASN1_OBJECT_push(reject, objtmp))
469                 goto err;
470             trustout = 1;
471             break;
472         case OPT_SETALIAS:
473             alias = opt_arg();
474             trustout = 1;
475             break;
476         case OPT_CERTOPT:
477             if (!set_cert_ex(&certflag, opt_arg()))
478                 goto opthelp;
479             break;
480         case OPT_NAMEOPT:
481             if (!set_nameopt(opt_arg()))
482                 goto opthelp;
483             break;
484         case OPT_ENGINE:
485             e = setup_engine(opt_arg(), 0);
486             break;
487         case OPT_EMAIL:
488             email = ++num;
489             break;
490         case OPT_OCSP_URI:
491             ocsp_uri = ++num;
492             break;
493         case OPT_SERIAL:
494             serial = ++num;
495             break;
496         case OPT_NEXT_SERIAL:
497             next_serial = ++num;
498             break;
499         case OPT_MODULUS:
500             modulus = ++num;
501             break;
502         case OPT_PUBKEY:
503             print_pubkey = ++num;
504             break;
505         case OPT_X509TOREQ:
506             x509toreq = 1;
507             break;
508         case OPT_TEXT:
509             text = ++num;
510             break;
511         case OPT_SUBJECT:
512             subject = ++num;
513             break;
514         case OPT_ISSUER:
515             issuer = ++num;
516             break;
517         case OPT_FINGERPRINT:
518             fingerprint = ++num;
519             break;
520         case OPT_HASH:
521             subject_hash = ++num;
522             break;
523         case OPT_ISSUER_HASH:
524             issuer_hash = ++num;
525             break;
526         case OPT_PURPOSE:
527             pprint = ++num;
528             break;
529         case OPT_STARTDATE:
530             startdate = ++num;
531             break;
532         case OPT_ENDDATE:
533             enddate = ++num;
534             break;
535         case OPT_NOOUT:
536             noout = ++num;
537             break;
538         case OPT_EXT:
539             ext = ++num;
540             ext_names = opt_arg();
541             break;
542         case OPT_NOCERT:
543             nocert = 1;
544             break;
545         case OPT_TRUSTOUT:
546             trustout = 1;
547             break;
548         case OPT_CLRTRUST:
549             clrtrust = ++num;
550             break;
551         case OPT_CLRREJECT:
552             clrreject = ++num;
553             break;
554         case OPT_ALIAS:
555             aliasout = ++num;
556             break;
557         case OPT_CACREATESERIAL:
558             CA_createserial = 1;
559             break;
560         case OPT_CLREXT:
561             clrext = 1;
562             break;
563         case OPT_OCSPID:
564             ocspid = ++num;
565             break;
566         case OPT_BADSIG:
567             badsig = 1;
568             break;
569 #ifndef OPENSSL_NO_MD5
570         case OPT_SUBJECT_HASH_OLD:
571             subject_hash_old = ++num;
572             break;
573         case OPT_ISSUER_HASH_OLD:
574             issuer_hash_old = ++num;
575             break;
576 #else
577         case OPT_SUBJECT_HASH_OLD:
578         case OPT_ISSUER_HASH_OLD:
579             break;
580 #endif
581         case OPT_DATES:
582             startdate = ++num;
583             enddate = ++num;
584             break;
585         case OPT_CHECKEND:
586             checkend = 1;
587             {
588                 ossl_intmax_t temp = 0;
589                 if (!opt_intmax(opt_arg(), &temp))
590                     goto opthelp;
591                 checkoffset = (time_t)temp;
592                 if ((ossl_intmax_t)checkoffset != temp) {
593                     BIO_printf(bio_err, "%s: Checkend time out of range %s\n",
594                                prog, opt_arg());
595                     goto opthelp;
596                 }
597             }
598             break;
599         case OPT_CHECKHOST:
600             checkhost = opt_arg();
601             break;
602         case OPT_CHECKEMAIL:
603             checkemail = opt_arg();
604             break;
605         case OPT_CHECKIP:
606             checkip = opt_arg();
607             break;
608         case OPT_PRESERVE_DATES:
609             preserve_dates = 1;
610             break;
611         case OPT_MD:
612             digest = opt_unknown();
613             break;
614         }
615     }
616     /* No extra arguments. */
617     if (!opt_check_rest_arg(NULL))
618         goto opthelp;
619 
620     if (!app_RAND_load())
621         goto err;
622 
623     if (!opt_check_md(digest))
624         goto opthelp;
625 
626     if (preserve_dates && not_before != NULL) {
627         BIO_printf(bio_err, "Cannot use -preserve_dates with -not_before option\n");
628         goto err;
629     }
630     if (preserve_dates && not_after != NULL) {
631         BIO_printf(bio_err, "Cannot use -preserve_dates with -not_after option\n");
632         goto err;
633     }
634     if (preserve_dates && days != UNSET_DAYS) {
635         BIO_printf(bio_err, "Cannot use -preserve_dates with -days option\n");
636         goto err;
637     }
638     if (days == UNSET_DAYS)
639         days = DEFAULT_DAYS;
640     else if (not_after != NULL)
641         BIO_printf(bio_err, "Warning: -not_after option overriding -days option\n");
642 
643     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
644         BIO_printf(bio_err, "Error getting password\n");
645         goto err;
646     }
647 
648     if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(),
649                                          app_get0_propq()))
650         goto err;
651 
652     if (newcert && infile != NULL) {
653         BIO_printf(bio_err, "The -in option cannot be used with -new\n");
654         goto err;
655     }
656     if (newcert && reqfile) {
657         BIO_printf(bio_err, "The -req option cannot be used with -new\n");
658         goto err;
659     }
660     if (privkeyfile != NULL) {
661         privkey = load_key(privkeyfile, keyformat, 0, passin, e, "private key");
662         if (privkey == NULL)
663             goto err;
664     }
665     if (pubkeyfile != NULL) {
666         if ((pubkey = load_pubkey(pubkeyfile, keyformat, 0, NULL, e,
667                                   "explicitly set public key")) == NULL)
668             goto err;
669     }
670 
671     if (newcert) {
672         if (subj == NULL) {
673             BIO_printf(bio_err,
674                        "The -new option requires a subject to be set using -subj\n");
675             goto err;
676         }
677         if (privkeyfile == NULL && pubkeyfile == NULL) {
678             BIO_printf(bio_err,
679                        "The -new option requires using the -key or -force_pubkey option\n");
680             goto err;
681         }
682     }
683     if (issu != NULL
684             && (fissu = parse_name(issu, chtype, multirdn, "issuer")) == NULL)
685         goto err;
686     if (subj != NULL
687             && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
688         goto err;
689 
690     if (CAkeyfile == NULL)
691         CAkeyfile = CAfile;
692     if (CAfile != NULL) {
693         if (privkeyfile != NULL) {
694             BIO_printf(bio_err, "Cannot use both -key/-signkey and -CA option\n");
695             goto err;
696         }
697     } else {
698 #define WARN_NO_CA(opt) BIO_printf(bio_err, \
699         "Warning: ignoring " opt " option since -CA option is not given\n");
700         if (CAkeyfile != NULL)
701             WARN_NO_CA("-CAkey");
702         if (CAkeyformat != FORMAT_UNDEF)
703             WARN_NO_CA("-CAkeyform");
704         if (CAformat != FORMAT_UNDEF)
705             WARN_NO_CA("-CAform");
706         if (CAserial != NULL)
707             WARN_NO_CA("-CAserial");
708         if (CA_createserial)
709             WARN_NO_CA("-CAcreateserial");
710     }
711 
712     if (extfile == NULL) {
713         if (extsect != NULL)
714             BIO_printf(bio_err,
715                        "Warning: ignoring -extensions option without -extfile\n");
716     } else {
717         X509V3_CTX ctx2;
718 
719         if ((extconf = app_load_config(extfile)) == NULL)
720             goto err;
721         if (extsect == NULL) {
722             extsect = app_conf_try_string(extconf, "default", "extensions");
723             if (extsect == NULL)
724                 extsect = "default";
725         }
726         X509V3_set_ctx_test(&ctx2);
727         X509V3_set_nconf(&ctx2, extconf);
728         if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
729             BIO_printf(bio_err,
730                        "Error checking extension section %s\n", extsect);
731             goto err;
732         }
733     }
734 
735     if (reqfile) {
736         if (infile == NULL && isatty(fileno_stdin()))
737             BIO_printf(bio_err,
738                        "Warning: Reading cert request from stdin since no -in option is given\n");
739         req = load_csr_autofmt(infile, informat, vfyopts,
740                                "certificate request input");
741         if (req == NULL)
742             goto err;
743 
744         if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) {
745             BIO_printf(bio_err, "Error unpacking public key from CSR\n");
746             goto err;
747         }
748         i = do_X509_REQ_verify(req, pkey, vfyopts);
749         if (i <= 0) {
750             BIO_printf(bio_err, i < 0
751                        ? "Error while verifying certificate request self-signature\n"
752                        : "Certificate request self-signature did not match the contents\n");
753             goto err;
754         }
755         BIO_printf(bio_err, "Certificate request self-signature ok\n");
756 
757         print_name(bio_err, "subject=", X509_REQ_get_subject_name(req));
758     } else if (!x509toreq && ext_copy != EXT_COPY_UNSET) {
759         BIO_printf(bio_err, "Warning: ignoring -copy_extensions since neither -x509toreq nor -req is given\n");
760     }
761 
762     if (reqfile || newcert) {
763         if (preserve_dates)
764             BIO_printf(bio_err,
765                        "Warning: ignoring -preserve_dates option with -req or -new\n");
766         preserve_dates = 0;
767         if (privkeyfile == NULL && CAkeyfile == NULL) {
768             BIO_printf(bio_err,
769                        "We need a private key to sign with, use -key or -CAkey or -CA with private key\n");
770             goto err;
771         }
772         if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
773             goto err;
774         if (CAfile == NULL && sno == NULL) {
775             sno = ASN1_INTEGER_new();
776             if (sno == NULL || !rand_serial(NULL, sno))
777                 goto err;
778         }
779         if (req != NULL && ext_copy != EXT_COPY_UNSET) {
780             if (clrext && ext_copy != EXT_COPY_NONE) {
781                 BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
782                 goto err;
783             } else if (!copy_extensions(x, req, ext_copy)) {
784                 BIO_printf(bio_err, "Error copying extensions from request\n");
785                 goto err;
786             }
787         }
788     } else {
789         if (infile == NULL && isatty(fileno_stdin()))
790             BIO_printf(bio_err,
791                        "Warning: Reading certificate from stdin since no -in or -new option is given\n");
792         x = load_cert_pass(infile, informat, 1, passin, "certificate");
793         if (x == NULL)
794             goto err;
795     }
796     if ((fsubj != NULL || req != NULL)
797         && !X509_set_subject_name(x, fsubj != NULL ? fsubj :
798                                   X509_REQ_get_subject_name(req)))
799         goto err;
800     if ((pubkey != NULL || privkey != NULL || req != NULL)
801         && !X509_set_pubkey(x, pubkey != NULL ? pubkey :
802                             privkey != NULL ? privkey :
803                             X509_REQ_get0_pubkey(req)))
804         goto err;
805 
806     if (CAfile != NULL) {
807         xca = load_cert_pass(CAfile, CAformat, 1, passin, "CA certificate");
808         if (xca == NULL)
809             goto err;
810     }
811 
812     out = bio_open_default(outfile, 'w', outformat);
813     if (out == NULL)
814         goto err;
815 
816     if (alias)
817         X509_alias_set1(x, (unsigned char *)alias, -1);
818 
819     if (clrtrust)
820         X509_trust_clear(x);
821     if (clrreject)
822         X509_reject_clear(x);
823 
824     if (trust != NULL) {
825         for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++)
826             X509_add1_trust_object(x, sk_ASN1_OBJECT_value(trust, i));
827     }
828 
829     if (reject != NULL) {
830         for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++)
831             X509_add1_reject_object(x, sk_ASN1_OBJECT_value(reject, i));
832     }
833 
834     if (clrext && ext_names != NULL)
835         BIO_printf(bio_err, "Warning: Ignoring -ext since -clrext is given\n");
836     for (i = X509_get_ext_count(x) - 1; i >= 0; i--) {
837         X509_EXTENSION *ex = X509_get_ext(x, i);
838         const char *sn = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ex)));
839 
840         if (clrext || (ext_names != NULL && strstr(ext_names, sn) == NULL))
841             X509_EXTENSION_free(X509_delete_ext(x, i));
842     }
843 
844     issuer_cert = x;
845     if (CAfile != NULL) {
846         issuer_cert = xca;
847         if (sno == NULL)
848             sno = x509_load_serial(CAfile, CAserial, CA_createserial);
849         if (sno == NULL)
850             goto err;
851         if (!x509toreq && !reqfile && !newcert && !self_signed(ctx, x))
852             goto err;
853     } else {
854         if (privkey != NULL && !cert_matches_key(x, privkey))
855             BIO_printf(bio_err,
856                        "Warning: Signature key and public key of cert do not match\n");
857     }
858 
859     if (sno != NULL && !X509_set_serialNumber(x, sno))
860         goto err;
861 
862     if (reqfile || newcert || privkey != NULL || CAfile != NULL) {
863         if (!preserve_dates && !set_cert_times(x, not_before, not_after, days, 1))
864             goto err;
865         if (fissu != NULL) {
866             if (!X509_set_issuer_name(x, fissu))
867                 goto err;
868         } else {
869             if (!X509_set_issuer_name(x, X509_get_subject_name(issuer_cert)))
870                 goto err;
871         }
872     }
873 
874     X509V3_set_ctx(&ext_ctx, issuer_cert, x, NULL, NULL, X509V3_CTX_REPLACE);
875     /* prepare fallback for AKID, but only if issuer cert equals subject cert */
876     if (CAfile == NULL) {
877         if (!X509V3_set_issuer_pkey(&ext_ctx, privkey))
878             goto err;
879     }
880     if (extconf != NULL && !x509toreq) {
881         X509V3_set_nconf(&ext_ctx, extconf);
882         if (!X509V3_EXT_add_nconf(extconf, &ext_ctx, extsect, x)) {
883             BIO_printf(bio_err,
884                        "Error adding extensions from section %s\n", extsect);
885             goto err;
886         }
887     }
888 
889     /* At this point the contents of the certificate x have been finished. */
890 
891     pkey = X509_get0_pubkey(x);
892     if ((print_pubkey != 0 || modulus != 0) && pkey == NULL) {
893         BIO_printf(bio_err, "Error getting public key\n");
894         goto err;
895     }
896 
897     if (x509toreq) { /* also works in conjunction with -req */
898         if (privkey == NULL) {
899             BIO_printf(bio_err, "Must specify request signing key using -key\n");
900             goto err;
901         }
902         if (clrext && ext_copy != EXT_COPY_NONE) {
903             BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
904             goto err;
905         }
906         if ((rq = x509_to_req(x, ext_copy, ext_names)) == NULL)
907             goto err;
908         if (extconf != NULL) {
909             X509V3_set_nconf(&ext_ctx, extconf);
910             if (!X509V3_EXT_REQ_add_nconf(extconf, &ext_ctx, extsect, rq)) {
911                 BIO_printf(bio_err,
912                            "Error adding request extensions from section %s\n", extsect);
913                 goto err;
914             }
915         }
916         if (!do_X509_REQ_sign(rq, privkey, digest, sigopts))
917             goto err;
918         if (!noout) {
919             if (outformat == FORMAT_ASN1) {
920                 X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT);
921                 i = i2d_X509_bio(out, x);
922             } else {
923                 i = PEM_write_bio_X509_REQ(out, rq);
924             }
925             if (!i) {
926                 BIO_printf(bio_err,
927                            "Unable to write certificate request\n");
928                 goto err;
929             }
930         }
931         noout = 1;
932     } else if (CAfile != NULL) {
933         if ((CAkey = load_key(CAkeyfile, CAkeyformat,
934                               0, passin, e, "CA private key")) == NULL)
935             goto err;
936         if (!X509_check_private_key(xca, CAkey)) {
937             BIO_printf(bio_err,
938                        "CA certificate and CA private key do not match\n");
939             goto err;
940         }
941 
942         if (!do_X509_sign(x, 0, CAkey, digest, sigopts, &ext_ctx))
943             goto err;
944     } else if (privkey != NULL) {
945         if (!do_X509_sign(x, 0, privkey, digest, sigopts, &ext_ctx))
946             goto err;
947     }
948     if (badsig) {
949         const ASN1_BIT_STRING *signature;
950 
951         X509_get0_signature(&signature, NULL, x);
952         corrupt_signature(signature);
953     }
954 
955     /* Process print options in the given order, as indicated by index i */
956     for (i = 1; i <= num; i++) {
957         if (i == issuer) {
958             print_name(out, "issuer=", X509_get_issuer_name(x));
959         } else if (i == subject) {
960             print_name(out, "subject=", X509_get_subject_name(x));
961         } else if (i == serial) {
962             BIO_printf(out, "serial=");
963             i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x));
964             BIO_printf(out, "\n");
965         } else if (i == next_serial) {
966             ASN1_INTEGER *ser;
967             BIGNUM *bnser = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x), NULL);
968 
969             if (bnser == NULL)
970                 goto err;
971             if (!BN_add_word(bnser, 1)
972                     || (ser = BN_to_ASN1_INTEGER(bnser, NULL)) == NULL) {
973                 BN_free(bnser);
974                 goto err;
975             }
976             BN_free(bnser);
977             i2a_ASN1_INTEGER(out, ser);
978             ASN1_INTEGER_free(ser);
979             BIO_puts(out, "\n");
980         } else if (i == email || i == ocsp_uri) {
981             STACK_OF(OPENSSL_STRING) *emlst =
982                 i == email ? X509_get1_email(x) : X509_get1_ocsp(x);
983 
984             for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
985                 BIO_printf(out, "%s\n", sk_OPENSSL_STRING_value(emlst, j));
986             X509_email_free(emlst);
987         } else if (i == aliasout) {
988             unsigned char *alstr = X509_alias_get0(x, NULL);
989 
990             if (alstr)
991                 BIO_printf(out, "%s\n", alstr);
992             else
993                 BIO_puts(out, "<No Alias>\n");
994         } else if (i == subject_hash) {
995             BIO_printf(out, "%08lx\n", X509_subject_name_hash(x));
996 #ifndef OPENSSL_NO_MD5
997         } else if (i == subject_hash_old) {
998             BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x));
999 #endif
1000         } else if (i == issuer_hash) {
1001             BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x));
1002 #ifndef OPENSSL_NO_MD5
1003         } else if (i == issuer_hash_old) {
1004             BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x));
1005 #endif
1006         } else if (i == pprint) {
1007             BIO_printf(out, "Certificate purposes:\n");
1008             for (j = 0; j < X509_PURPOSE_get_count(); j++)
1009                 purpose_print(out, x, X509_PURPOSE_get0(j));
1010         } else if (i == modulus) {
1011             BIO_printf(out, "Modulus=");
1012             if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) {
1013                 BIGNUM *n = NULL;
1014 
1015                 /* Every RSA key has an 'n' */
1016                 EVP_PKEY_get_bn_param(pkey, "n", &n);
1017                 BN_print(out, n);
1018                 BN_free(n);
1019             } else if (EVP_PKEY_is_a(pkey, "DSA")) {
1020                 BIGNUM *dsapub = NULL;
1021 
1022                 /* Every DSA key has a 'pub' */
1023                 EVP_PKEY_get_bn_param(pkey, "pub", &dsapub);
1024                 BN_print(out, dsapub);
1025                 BN_free(dsapub);
1026             } else {
1027                 BIO_printf(out, "No modulus for this public key type");
1028             }
1029             BIO_printf(out, "\n");
1030         } else if (i == print_pubkey) {
1031             PEM_write_bio_PUBKEY(out, pkey);
1032         } else if (i == text) {
1033             X509_print_ex(out, x, get_nameopt(), certflag);
1034         } else if (i == startdate) {
1035             BIO_puts(out, "notBefore=");
1036             ASN1_TIME_print_ex(out, X509_get0_notBefore(x), dateopt);
1037             BIO_puts(out, "\n");
1038         } else if (i == enddate) {
1039             BIO_puts(out, "notAfter=");
1040             ASN1_TIME_print_ex(out, X509_get0_notAfter(x), dateopt);
1041             BIO_puts(out, "\n");
1042         } else if (i == fingerprint) {
1043             unsigned int n;
1044             unsigned char md[EVP_MAX_MD_SIZE];
1045             const char *fdigname = digest;
1046             EVP_MD *fdig;
1047             int digres;
1048 
1049             if (fdigname == NULL)
1050                 fdigname = "SHA1";
1051 
1052             if ((fdig = EVP_MD_fetch(app_get0_libctx(), fdigname,
1053                                      app_get0_propq())) == NULL) {
1054                 BIO_printf(bio_err, "Unknown digest\n");
1055                 goto err;
1056             }
1057             digres = X509_digest(x, fdig, md, &n);
1058             EVP_MD_free(fdig);
1059             if (!digres) {
1060                 BIO_printf(bio_err, "Out of memory\n");
1061                 goto err;
1062             }
1063 
1064             BIO_printf(out, "%s Fingerprint=", fdigname);
1065             for (j = 0; j < (int)n; j++)
1066                 BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':');
1067         } else if (i == ocspid) {
1068             X509_ocspid_print(out, x);
1069         } else if (i == ext) {
1070             print_x509v3_exts(out, x, ext_names);
1071         }
1072     }
1073 
1074     if (checkend) {
1075         time_t tcheck = time(NULL) + checkoffset;
1076 
1077         ret = X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0;
1078         if (ret)
1079             BIO_printf(out, "Certificate will expire\n");
1080         else
1081             BIO_printf(out, "Certificate will not expire\n");
1082         goto end;
1083     }
1084 
1085     if (!check_cert_attributes(out, x, checkhost, checkemail, checkip, 1))
1086         goto err;
1087 
1088     if (noout || nocert) {
1089         ret = 0;
1090         goto end;
1091     }
1092 
1093     if (outformat == FORMAT_ASN1) {
1094         i = i2d_X509_bio(out, x);
1095     } else if (outformat == FORMAT_PEM) {
1096         if (trustout)
1097             i = PEM_write_bio_X509_AUX(out, x);
1098         else
1099             i = PEM_write_bio_X509(out, x);
1100     } else {
1101         BIO_printf(bio_err, "Bad output format specified for outfile\n");
1102         goto err;
1103     }
1104     if (!i) {
1105         BIO_printf(bio_err, "Unable to write certificate\n");
1106         goto err;
1107     }
1108 
1109     ret = 0;
1110     goto end;
1111 
1112  err:
1113     ERR_print_errors(bio_err);
1114 
1115  end:
1116     NCONF_free(extconf);
1117     BIO_free_all(out);
1118     X509_STORE_free(ctx);
1119     X509_NAME_free(fissu);
1120     X509_NAME_free(fsubj);
1121     X509_REQ_free(req);
1122     X509_free(x);
1123     X509_free(xca);
1124     EVP_PKEY_free(privkey);
1125     EVP_PKEY_free(CAkey);
1126     EVP_PKEY_free(pubkey);
1127     sk_OPENSSL_STRING_free(sigopts);
1128     sk_OPENSSL_STRING_free(vfyopts);
1129     X509_REQ_free(rq);
1130     ASN1_INTEGER_free(sno);
1131     sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
1132     sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
1133     release_engine(e);
1134     clear_free(passin);
1135     return ret;
1136 }
1137 
x509_load_serial(const char * CAfile,const char * serialfile,int create)1138 static ASN1_INTEGER *x509_load_serial(const char *CAfile,
1139                                       const char *serialfile, int create)
1140 {
1141     char *buf = NULL;
1142     ASN1_INTEGER *bs = NULL;
1143     BIGNUM *serial = NULL;
1144     int defaultfile = 0, file_exists;
1145 
1146     if (serialfile == NULL) {
1147         const char *p = strrchr(CAfile, '.');
1148         size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile);
1149 
1150         buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer");
1151         memcpy(buf, CAfile, len);
1152         memcpy(buf + len, POSTFIX, sizeof(POSTFIX));
1153         serialfile = buf;
1154         defaultfile = 1;
1155     }
1156 
1157     serial = load_serial(serialfile, &file_exists, create || defaultfile, NULL);
1158     if (serial == NULL)
1159         goto end;
1160 
1161     if (!BN_add_word(serial, 1)) {
1162         BIO_printf(bio_err, "Serial number increment failure\n");
1163         goto end;
1164     }
1165 
1166     if (file_exists || create)
1167         save_serial(serialfile, NULL, serial, &bs);
1168     else
1169         bs = BN_to_ASN1_INTEGER(serial, NULL);
1170 
1171  end:
1172     OPENSSL_free(buf);
1173     BN_free(serial);
1174     return bs;
1175 }
1176 
callb(int ok,X509_STORE_CTX * ctx)1177 static int callb(int ok, X509_STORE_CTX *ctx)
1178 {
1179     int err;
1180     X509 *err_cert;
1181 
1182     /*
1183      * It is ok to use a self-signed certificate. This case will catch both
1184      * the initial ok == 0 and the final ok == 1 calls to this function.
1185      */
1186     err = X509_STORE_CTX_get_error(ctx);
1187     if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1188         return 1;
1189 
1190     if (!ok) {
1191         err_cert = X509_STORE_CTX_get_current_cert(ctx);
1192         print_name(bio_err, "subject=", X509_get_subject_name(err_cert));
1193         BIO_printf(bio_err,
1194                    "Error with certificate - error %d at depth %d\n%s\n", err,
1195                    X509_STORE_CTX_get_error_depth(ctx),
1196                    X509_verify_cert_error_string(err));
1197         return 1;
1198     }
1199 
1200     return 1;
1201 }
1202 
purpose_print(BIO * bio,X509 * cert,X509_PURPOSE * pt)1203 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1204 {
1205     int id, i, idret;
1206     const char *pname;
1207     id = X509_PURPOSE_get_id(pt);
1208     pname = X509_PURPOSE_get0_name(pt);
1209     for (i = 0; i < 2; i++) {
1210         idret = X509_check_purpose(cert, id, i);
1211         BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
1212         if (idret == 1)
1213             BIO_printf(bio, "Yes\n");
1214         else if (idret == 0)
1215             BIO_printf(bio, "No\n");
1216         else
1217             BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1218     }
1219     return 1;
1220 }
1221 
parse_ext_names(char * names,const char ** result)1222 static int parse_ext_names(char *names, const char **result)
1223 {
1224     char *p, *q;
1225     int cnt = 0, len = 0;
1226 
1227     p = q = names;
1228     len = strlen(names);
1229 
1230     while (q - names <= len) {
1231         if (*q != ',' && *q != '\0') {
1232             q++;
1233             continue;
1234         }
1235         if (p != q) {
1236             /* found */
1237             if (result != NULL) {
1238                 result[cnt] = p;
1239                 *q = '\0';
1240             }
1241             cnt++;
1242         }
1243         p = ++q;
1244     }
1245 
1246     return cnt;
1247 }
1248 
print_x509v3_exts(BIO * bio,X509 * x,const char * ext_names)1249 static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names)
1250 {
1251     const STACK_OF(X509_EXTENSION) *exts = NULL;
1252     STACK_OF(X509_EXTENSION) *exts2 = NULL;
1253     X509_EXTENSION *ext = NULL;
1254     ASN1_OBJECT *obj;
1255     int i, j, ret = 0, num, nn = 0;
1256     const char *sn, **names = NULL;
1257     char *tmp_ext_names = NULL;
1258 
1259     exts = X509_get0_extensions(x);
1260     if ((num = sk_X509_EXTENSION_num(exts)) <= 0) {
1261         BIO_printf(bio_err, "No extensions in certificate\n");
1262         ret = 1;
1263         goto end;
1264     }
1265 
1266     /* parse comma separated ext name string */
1267     if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL)
1268         goto end;
1269     if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) {
1270         BIO_printf(bio, "Invalid extension names: %s\n", ext_names);
1271         goto end;
1272     }
1273     if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL)
1274         goto end;
1275     parse_ext_names(tmp_ext_names, names);
1276 
1277     for (i = 0; i < num; i++) {
1278         ext = sk_X509_EXTENSION_value(exts, i);
1279 
1280         /* check if this ext is what we want */
1281         obj = X509_EXTENSION_get_object(ext);
1282         sn = OBJ_nid2sn(OBJ_obj2nid(obj));
1283         if (sn == NULL || strcmp(sn, "UNDEF") == 0)
1284             continue;
1285 
1286         for (j = 0; j < nn; j++) {
1287             if (strcmp(sn, names[j]) == 0) {
1288                 /* push the extension into a new stack */
1289                 if (exts2 == NULL
1290                     && (exts2 = sk_X509_EXTENSION_new_null()) == NULL)
1291                     goto end;
1292                 if (!sk_X509_EXTENSION_push(exts2, ext))
1293                     goto end;
1294             }
1295         }
1296     }
1297 
1298     if (!sk_X509_EXTENSION_num(exts2)) {
1299         BIO_printf(bio, "No extensions matched with %s\n", ext_names);
1300         ret = 1;
1301         goto end;
1302     }
1303 
1304     ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0);
1305  end:
1306     sk_X509_EXTENSION_free(exts2);
1307     OPENSSL_free(names);
1308     OPENSSL_free(tmp_ext_names);
1309     return ret;
1310 }
1311