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