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