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