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