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