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