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