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