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