2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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
15 #include <openssl/bio.h>
16 #include <openssl/asn1.h>
17 #include <openssl/err.h>
18 #include <openssl/bn.h>
19 #include <openssl/evp.h>
20 #include <openssl/x509.h>
21 #include <openssl/x509v3.h>
22 #include <openssl/objects.h>
23 #include <openssl/pem.h>
24 #include <openssl/rsa.h>
25 #ifndef OPENSSL_NO_DSA
26 # include <openssl/dsa.h>
30 #define POSTFIX ".srl"
33 static int callb(int ok, X509_STORE_CTX *ctx);
34 static int sign(X509 *x, EVP_PKEY *pkey, X509 *issuer,
35 STACK_OF(OPENSSL_STRING) *sigopts,
37 const EVP_MD *digest, CONF *conf, const char *section,
39 static int x509_certify(X509_STORE *ctx, const char *CAfile, const EVP_MD *digest,
40 X509 *x, X509 *xca, EVP_PKEY *pkey,
41 STACK_OF(OPENSSL_STRING) *sigopts, const char *serialfile,
42 int create, int days, int clrext, CONF *conf,
43 const char *section, ASN1_INTEGER *sno, int reqfile,
45 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
46 static int print_x509v3_exts(BIO *bio, X509 *x, const char *exts);
48 typedef enum OPTION_choice {
49 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
50 OPT_INFORM, OPT_OUTFORM, OPT_KEYFORM, OPT_REQ, OPT_CAFORM,
51 OPT_CAKEYFORM, OPT_VFYOPT, OPT_SIGOPT, OPT_DAYS, OPT_PASSIN, OPT_EXTFILE,
52 OPT_EXTENSIONS, OPT_IN, OPT_OUT, OPT_SIGNKEY, OPT_CA, OPT_CAKEY,
53 OPT_CASERIAL, OPT_SET_SERIAL, OPT_NEW, OPT_FORCE_PUBKEY, OPT_SUBJ,
54 OPT_ADDTRUST, OPT_ADDREJECT, OPT_SETALIAS, OPT_CERTOPT, OPT_NAMEOPT,
55 OPT_EMAIL, OPT_OCSP_URI, OPT_SERIAL, OPT_NEXT_SERIAL,
56 OPT_MODULUS, OPT_PUBKEY, OPT_X509TOREQ, OPT_TEXT, OPT_HASH,
57 OPT_ISSUER_HASH, OPT_SUBJECT, OPT_ISSUER, OPT_FINGERPRINT, OPT_DATES,
58 OPT_PURPOSE, OPT_STARTDATE, OPT_ENDDATE, OPT_CHECKEND, OPT_CHECKHOST,
59 OPT_CHECKEMAIL, OPT_CHECKIP, OPT_NOOUT, OPT_TRUSTOUT, OPT_CLRTRUST,
60 OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID,
63 OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES,
64 OPT_R_ENUM, OPT_PROV_ENUM, OPT_EXT
67 const OPTIONS x509_options[] = {
68 OPT_SECTION("General"),
69 {"help", OPT_HELP, '-', "Display this summary"},
70 #ifndef OPENSSL_NO_ENGINE
71 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
74 {"inform", OPT_INFORM, 'f',
75 "CSR input format (DER or PEM) - default PEM"},
76 {"in", OPT_IN, '<', "Input file - default stdin"},
77 {"passin", OPT_PASSIN, 's', "Private key and cert file pass-phrase source"},
78 {"outform", OPT_OUTFORM, 'f',
79 "Output format (DER or PEM) - default PEM"},
80 {"out", OPT_OUT, '>', "Output file - default stdout"},
81 {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"},
82 {"req", OPT_REQ, '-', "Input is a certificate request, sign and output"},
83 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
85 OPT_SECTION("Output"),
86 {"serial", OPT_SERIAL, '-', "Print serial number value"},
87 {"subject_hash", OPT_HASH, '-', "Print subject hash value"},
88 {"issuer_hash", OPT_ISSUER_HASH, '-', "Print issuer hash value"},
89 {"hash", OPT_HASH, '-', "Synonym for -subject_hash"},
90 {"subject", OPT_SUBJECT, '-', "Print subject DN"},
91 {"issuer", OPT_ISSUER, '-', "Print issuer DN"},
92 {"email", OPT_EMAIL, '-', "Print email address(es)"},
93 {"purpose", OPT_PURPOSE, '-', "Print out certificate purposes"},
94 {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"},
95 {"pubkey", OPT_PUBKEY, '-', "Output the public key"},
96 {"fingerprint", OPT_FINGERPRINT, '-', "Print the certificate fingerprint"},
97 {"alias", OPT_ALIAS, '-', "Output certificate alias"},
98 {"noout", OPT_NOOUT, '-', "No output, just status"},
99 {"ocspid", OPT_OCSPID, '-',
100 "Print OCSP hash values for the subject name and public key"},
101 {"ocsp_uri", OPT_OCSP_URI, '-', "Print OCSP Responder URL(s)"},
102 {"nocert", OPT_NOCERT, '-', "No certificate output"},
103 {"trustout", OPT_TRUSTOUT, '-', "Output a trusted certificate"},
104 {"x509toreq", OPT_X509TOREQ, '-',
105 "Output a certification request object"},
106 {"checkend", OPT_CHECKEND, 'M',
107 "Check whether the cert expires in the next arg seconds"},
108 {OPT_MORE_STR, 1, 1, "Exit 1 if so, 0 if not"},
109 {"text", OPT_TEXT, '-', "Print the certificate in text form"},
110 {"ext", OPT_EXT, 's', "Print various X509V3 extensions"},
111 #ifndef OPENSSL_NO_MD5
112 {"subject_hash_old", OPT_SUBJECT_HASH_OLD, '-',
113 "Print old-style (MD5) subject hash value"},
114 {"issuer_hash_old", OPT_ISSUER_HASH_OLD, '-',
115 "Print old-style (MD5) issuer hash value"},
117 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
119 OPT_SECTION("Certificate"),
120 {"startdate", OPT_STARTDATE, '-', "Set notBefore field"},
121 {"enddate", OPT_ENDDATE, '-', "Set notAfter field"},
122 {"dates", OPT_DATES, '-', "Both Before and After dates"},
123 {"clrtrust", OPT_CLRTRUST, '-', "Clear all trusted purposes"},
124 {"clrext", OPT_CLREXT, '-', "Clear all certificate extensions"},
125 {"addtrust", OPT_ADDTRUST, 's', "Trust certificate for a given purpose"},
126 {"addreject", OPT_ADDREJECT, 's',
127 "Reject certificate for a given purpose"},
128 {"setalias", OPT_SETALIAS, 's', "Set certificate alias"},
129 {"days", OPT_DAYS, 'n',
130 "How long till expiry of a signed certificate - def 30 days"},
131 {"signkey", OPT_SIGNKEY, 's', "Self-sign cert with arg"},
132 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
133 {"extensions", OPT_EXTENSIONS, 's', "Section from config file to use"},
134 {"certopt", OPT_CERTOPT, 's', "Various certificate text options"},
135 {"checkhost", OPT_CHECKHOST, 's', "Check certificate matches host"},
136 {"checkemail", OPT_CHECKEMAIL, 's', "Check certificate matches email"},
137 {"checkip", OPT_CHECKIP, 's', "Check certificate matches ipaddr"},
138 {"force_pubkey", OPT_FORCE_PUBKEY, '<', "Force the key to put inside certificate"},
139 {"subj", OPT_SUBJ, 's', "Set or override certificate subject (and issuer)"},
142 {"CA", OPT_CA, '<', "Set the CA certificate, must be PEM format"},
143 {"CAkey", OPT_CAKEY, 's',
144 "The CA key, must be PEM format; if not in CAfile"},
145 {"extfile", OPT_EXTFILE, '<', "File with X509V3 extensions to add"},
148 {"CAform", OPT_CAFORM, 'F', "CA cert format (PEM/DER/P12); has no effect"},
149 {"CAkeyform", OPT_CAKEYFORM, 'E', "CA key format (ENGINE, other values ignored)"},
150 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
151 {"CAcreateserial", OPT_CACREATESERIAL, '-',
152 "Create serial number file if it does not exist"},
153 {"CAserial", OPT_CASERIAL, 's', "Serial file"},
154 {"new", OPT_NEW, '-', "Generate a certificate from scratch"},
155 {"next_serial", OPT_NEXT_SERIAL, '-', "Increment current certificate serial number"},
156 {"clrreject", OPT_CLRREJECT, '-',
157 "Clears all the prohibited or rejected uses of the certificate"},
158 {"badsig", OPT_BADSIG, '-', "Corrupt last byte of certificate signature (for test)"},
159 {"", OPT_MD, '-', "Any supported digest"},
160 {"preserve_dates", OPT_PRESERVE_DATES, '-', "preserve existing dates when signing"},
164 int x509_main(int argc, char **argv)
166 ASN1_INTEGER *sno = NULL;
167 ASN1_OBJECT *objtmp = NULL;
169 CONF *extconf = NULL;
170 EVP_PKEY *Upkey = NULL, *CApkey = NULL, *fkey = NULL;
173 X509_NAME *fsubj = NULL;
174 const unsigned long chtype = MBSTRING_ASC;
175 const int multirdn = 1;
176 STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
177 STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL;
178 X509 *x = NULL, *xca = NULL;
179 X509_REQ *req = NULL, *rq = NULL;
180 X509_STORE *ctx = NULL;
181 const EVP_MD *digest = NULL;
182 char *CAkeyfile = NULL, *CAserial = NULL, *fkeyfile = NULL, *alias = NULL;
183 char *checkhost = NULL, *checkemail = NULL, *checkip = NULL, *exts = NULL;
184 char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL;
185 char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL;
187 int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0, pprint = 0;
188 int CAformat = FORMAT_PEM, CAkeyformat = FORMAT_PEM;
189 int fingerprint = 0, reqfile = 0, checkend = 0;
190 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyformat = FORMAT_PEM;
191 int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0;
192 int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0;
193 int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0;
194 int ret = 1, i, num = 0, badsig = 0, clrext = 0, nocert = 0;
195 int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0;
197 time_t checkoffset = 0;
198 unsigned long certflag = 0;
199 int preserve_dates = 0;
202 #ifndef OPENSSL_NO_MD5
203 int subject_hash_old = 0, issuer_hash_old = 0;
206 ctx = X509_STORE_new();
209 X509_STORE_set_verify_cb(ctx, callb);
211 prog = opt_init(argc, argv, x509_options);
212 while ((o = opt_next()) != OPT_EOF) {
217 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
220 opt_help(x509_options);
224 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
231 if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
235 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
239 if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAformat))
243 if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAkeyformat))
255 sigopts = sk_OPENSSL_STRING_new_null();
256 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
261 vfyopts = sk_OPENSSL_STRING_new_null();
262 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
268 days = atoi(opt_arg());
271 passinarg = opt_arg();
281 if (!opt_provider(o))
296 CAkeyfile = opt_arg();
299 CAserial = opt_arg();
303 BIO_printf(bio_err, "Serial number supplied twice\n");
306 if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL)
312 case OPT_FORCE_PUBKEY:
313 fkeyfile = opt_arg();
319 if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
321 "%s: Invalid trust object value %s\n",
325 if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL)
327 sk_ASN1_OBJECT_push(trust, objtmp);
332 if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
334 "%s: Invalid reject object value %s\n",
339 && (reject = sk_ASN1_OBJECT_new_null()) == NULL)
341 sk_ASN1_OBJECT_push(reject, objtmp);
350 if (!set_cert_ex(&certflag, opt_arg()))
354 if (!set_nameopt(opt_arg()))
358 e = setup_engine(opt_arg(), 0);
369 case OPT_NEXT_SERIAL:
390 case OPT_FINGERPRINT:
394 subject_hash = ++num;
396 case OPT_ISSUER_HASH:
430 case OPT_CACREATESERIAL:
431 CA_createserial = ++num;
442 #ifndef OPENSSL_NO_MD5
443 case OPT_SUBJECT_HASH_OLD:
444 subject_hash_old = ++num;
446 case OPT_ISSUER_HASH_OLD:
447 issuer_hash_old = ++num;
450 case OPT_SUBJECT_HASH_OLD:
451 case OPT_ISSUER_HASH_OLD:
462 if (!opt_imax(opt_arg(), &temp))
464 checkoffset = (time_t)temp;
465 if ((intmax_t)checkoffset != temp) {
466 BIO_printf(bio_err, "%s: Checkend time out of range %s\n",
473 checkhost = opt_arg();
476 checkemail = opt_arg();
481 case OPT_PRESERVE_DATES:
482 if (days != DEF_DAYS)
487 if (!opt_md(opt_unknown(), &digest))
492 /* No extra arguments. */
493 argc = opt_num_rest();
497 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
498 BIO_printf(bio_err, "Error getting password\n");
502 if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(),
504 ERR_print_errors(bio_err);
508 if (newcert && infile != NULL) {
509 BIO_printf(bio_err, "The -in option must not be used since -new is set\n");
512 if (newcert && fkeyfile == NULL) {
514 "The -new option requires a public key to be set using -force_pubkey\n");
517 if (fkeyfile != NULL) {
518 fkey = load_pubkey(fkeyfile, keyformat, 0, NULL, e, "forced key");
523 if (newcert && subj == NULL) {
525 "The -new option requires a subject to be set using -subj\n");
529 && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
532 if (CAkeyfile == NULL && CA_flag && CAformat == FORMAT_PEM) {
534 } else if (CA_flag && CAkeyfile == NULL) {
536 "Need to specify a CAkey if using the CA command\n");
538 } else if (!CA_flag && CAkeyfile != NULL) {
540 "Ignoring -CAkey option since no -CA option is given\n");
543 if (extfile != NULL) {
545 if ((extconf = app_load_config(extfile)) == NULL)
547 if (extsect == NULL) {
548 extsect = NCONF_get_string(extconf, "default", "extensions");
549 if (extsect == NULL) {
554 X509V3_set_ctx_test(&ctx2);
555 X509V3_set_nconf(&ctx2, extconf);
556 if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
558 "Error checking extension section %s\n", extsect);
559 ERR_print_errors(bio_err);
567 req = load_csr(infile, informat, "certificate request input");
571 if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) {
572 BIO_printf(bio_err, "Error unpacking public key\n");
575 i = do_X509_REQ_verify(req, pkey, vfyopts);
577 BIO_printf(bio_err, "Request self-signature verification error\n");
578 ERR_print_errors(bio_err);
583 "Request self-signature did not match the certificate request\n");
586 BIO_printf(bio_err, "Request self-signature ok\n");
589 print_name(bio_err, "subject=", X509_REQ_get_subject_name(req),
593 if (reqfile || newcert) {
596 if (!sign_flag && CAkeyfile == NULL) {
598 "We need a private key to sign with, use -signkey or -CAkey or -CA <file> with private key\n");
601 if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
605 sno = ASN1_INTEGER_new();
606 if (sno == NULL || !rand_serial(NULL, sno))
608 if (!X509_set_serialNumber(x, sno))
610 ASN1_INTEGER_free(sno);
612 } else if (!X509_set_serialNumber(x, sno)) {
616 n = req == NULL ? fsubj : X509_REQ_get_subject_name(req);
617 if (!X509_set_issuer_name(x, n) || !X509_set_subject_name(x, n))
619 if (!set_cert_times(x, NULL, NULL, days))
622 if (!X509_set_pubkey(x, fkey != NULL ? fkey : X509_REQ_get0_pubkey(req)))
625 x = load_cert_pass(infile, 1, passin, "certificate");
628 if (fkey != NULL && !X509_set_pubkey(x, fkey))
630 if (fsubj != NULL && !X509_set_subject_name(x, fsubj))
635 xca = load_cert_pass(CAfile, 1, passin, "CA certificate");
640 out = bio_open_default(outfile, 'w', outformat);
644 if (!noout || text || next_serial)
645 OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3");
648 X509_alias_set1(x, (unsigned char *)alias, -1);
653 X509_reject_clear(x);
656 for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
657 objtmp = sk_ASN1_OBJECT_value(trust, i);
658 X509_add1_trust_object(x, objtmp);
663 if (reject != NULL) {
664 for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
665 objtmp = sk_ASN1_OBJECT_value(reject, i);
666 X509_add1_reject_object(x, objtmp);
672 const ASN1_BIT_STRING *signature;
674 X509_get0_signature(&signature, NULL, x);
675 corrupt_signature(signature);
679 for (i = 1; i <= num; i++) {
681 print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt());
682 } else if (subject == i) {
683 print_name(out, "subject=",
684 X509_get_subject_name(x), get_nameopt());
685 } else if (serial == i) {
686 BIO_printf(out, "serial=");
687 i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x));
688 BIO_printf(out, "\n");
689 } else if (next_serial == i) {
690 ASN1_INTEGER *ser = X509_get_serialNumber(x);
691 BIGNUM *bnser = ASN1_INTEGER_to_BN(ser, NULL);
695 if (!BN_add_word(bnser, 1))
697 ser = BN_to_ASN1_INTEGER(bnser, NULL);
701 i2a_ASN1_INTEGER(out, ser);
702 ASN1_INTEGER_free(ser);
704 } else if (email == i || ocsp_uri == i) {
706 STACK_OF(OPENSSL_STRING) *emlst;
708 emlst = X509_get1_email(x);
710 emlst = X509_get1_ocsp(x);
711 for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
712 BIO_printf(out, "%s\n",
713 sk_OPENSSL_STRING_value(emlst, j));
714 X509_email_free(emlst);
715 } else if (aliasout == i) {
716 unsigned char *alstr;
717 alstr = X509_alias_get0(x, NULL);
719 BIO_printf(out, "%s\n", alstr);
721 BIO_puts(out, "<No Alias>\n");
722 } else if (subject_hash == i) {
723 BIO_printf(out, "%08lx\n", X509_subject_name_hash(x));
725 #ifndef OPENSSL_NO_MD5
726 else if (subject_hash_old == i) {
727 BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x));
730 else if (issuer_hash == i) {
731 BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x));
733 #ifndef OPENSSL_NO_MD5
734 else if (issuer_hash_old == i) {
735 BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x));
738 else if (pprint == i) {
741 BIO_printf(out, "Certificate purposes:\n");
742 for (j = 0; j < X509_PURPOSE_get_count(); j++) {
743 ptmp = X509_PURPOSE_get0(j);
744 purpose_print(out, x, ptmp);
746 } else if (modulus == i) {
749 pkey = X509_get0_pubkey(x);
751 BIO_printf(bio_err, "Modulus=unavailable\n");
752 ERR_print_errors(bio_err);
755 BIO_printf(out, "Modulus=");
756 if (EVP_PKEY_is_a(pkey, "RSA")) {
759 /* Every RSA key has an 'n' */
760 EVP_PKEY_get_bn_param(pkey, "n", &n);
763 } else if (EVP_PKEY_is_a(pkey, "DSA")) {
766 /* Every DSA key has an 'pub' */
767 EVP_PKEY_get_bn_param(pkey, "pub", &dsapub);
768 BN_print(out, dsapub);
771 BIO_printf(out, "Wrong Algorithm type");
773 BIO_printf(out, "\n");
774 } else if (pubkey == i) {
777 pkey = X509_get0_pubkey(x);
779 BIO_printf(bio_err, "Error getting public key\n");
780 ERR_print_errors(bio_err);
783 PEM_write_bio_PUBKEY(out, pkey);
784 } else if (text == i) {
785 X509_print_ex(out, x, get_nameopt(), certflag);
786 } else if (startdate == i) {
787 BIO_puts(out, "notBefore=");
788 ASN1_TIME_print(out, X509_get0_notBefore(x));
790 } else if (enddate == i) {
791 BIO_puts(out, "notAfter=");
792 ASN1_TIME_print(out, X509_get0_notAfter(x));
794 } else if (fingerprint == i) {
797 unsigned char md[EVP_MAX_MD_SIZE];
798 const EVP_MD *fdig = digest;
803 if (!X509_digest(x, fdig, md, &n)) {
804 BIO_printf(bio_err, "Out of memory\n");
807 BIO_printf(out, "%s Fingerprint=",
808 OBJ_nid2sn(EVP_MD_type(fdig)));
809 for (j = 0; j < (int)n; j++) {
810 BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n)
815 /* should be in the library */
816 else if (sign_flag == i && x509req == 0) {
818 Upkey = load_key(keyfile, keyformat, 0,
819 passin, e, "private key");
823 if (fkey == NULL && !X509_set_pubkey(x, Upkey))
825 if (!sign(x, Upkey, x /* self-issuing */, sigopts, days, clrext,
826 digest, extconf, extsect, preserve_dates)) {
827 ERR_print_errors(bio_err);
830 } else if (CA_flag == i) {
831 if (CAkeyfile != NULL) {
832 CApkey = load_key(CAkeyfile, CAkeyformat,
833 0, passin, e, "CA private key");
838 if (!x509_certify(ctx, CAfile, digest, x, xca,
840 CAserial, CA_createserial, days, clrext,
841 extconf, extsect, sno, reqfile, preserve_dates))
843 } else if (x509req == i) {
846 if (keyfile == NULL) {
847 BIO_printf(bio_err, "No request key file specified\n");
850 pk = load_key(keyfile, keyformat, 0,
851 passin, e, "request key");
856 rq = X509_to_X509_REQ(x, pk, digest);
859 ERR_print_errors(bio_err);
863 X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT);
864 PEM_write_bio_X509_REQ(out, rq);
867 } else if (ocspid == i) {
868 X509_ocspid_print(out, x);
869 } else if (ext == i) {
870 print_x509v3_exts(out, x, exts);
876 time_t tcheck = time(NULL) + checkoffset;
878 if (X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0) {
879 BIO_printf(out, "Certificate will expire\n");
882 BIO_printf(out, "Certificate will not expire\n");
888 print_cert_checks(out, x, checkhost, checkemail, checkip);
890 if (noout || nocert) {
895 if (outformat == FORMAT_ASN1) {
896 i = i2d_X509_bio(out, x);
897 } else if (outformat == FORMAT_PEM) {
899 i = PEM_write_bio_X509_AUX(out, x);
901 i = PEM_write_bio_X509(out, x);
903 BIO_printf(bio_err, "Bad output format specified for outfile\n");
907 BIO_printf(bio_err, "Unable to write certificate\n");
908 ERR_print_errors(bio_err);
915 X509_STORE_free(ctx);
916 X509_NAME_free(fsubj);
920 EVP_PKEY_free(Upkey);
921 EVP_PKEY_free(CApkey);
923 sk_OPENSSL_STRING_free(sigopts);
924 sk_OPENSSL_STRING_free(vfyopts);
926 ASN1_INTEGER_free(sno);
927 sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
928 sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
929 ASN1_OBJECT_free(objtmp);
935 static ASN1_INTEGER *x509_load_serial(const char *CAfile,
936 const char *serialfile, int create)
939 ASN1_INTEGER *bs = NULL;
940 BIGNUM *serial = NULL;
942 if (serialfile == NULL) {
943 const char *p = strrchr(CAfile, '.');
944 size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile);
946 buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer");
947 memcpy(buf, CAfile, len);
948 memcpy(buf + len, POSTFIX, sizeof(POSTFIX));
952 serial = load_serial(serialfile, create, NULL);
956 if (!BN_add_word(serial, 1)) {
957 BIO_printf(bio_err, "Serial number increment failure\n");
961 if (!save_serial(serialfile, NULL, serial, &bs))
970 static int x509_certify(X509_STORE *ctx, const char *CAfile, const EVP_MD *digest,
971 X509 *x, X509 *xca, EVP_PKEY *pkey,
972 STACK_OF(OPENSSL_STRING) *sigopts,
973 const char *serialfile, int create,
974 int days, int clrext, CONF *conf, const char *section,
975 ASN1_INTEGER *sno, int reqfile, int preserve_dates)
978 ASN1_INTEGER *bs = NULL;
979 X509_STORE_CTX *xsc = NULL;
982 upkey = X509_get0_pubkey(xca);
984 BIO_printf(bio_err, "Error obtaining CA X509 public key\n");
987 EVP_PKEY_copy_parameters(upkey, pkey);
989 xsc = X509_STORE_CTX_new();
990 if (xsc == NULL || !X509_STORE_CTX_init(xsc, ctx, x, NULL)) {
991 BIO_printf(bio_err, "Error initialising X509 store\n");
996 else if ((bs = x509_load_serial(CAfile, serialfile, create)) == NULL)
1000 * NOTE: this certificate can/should be self-signed, unless it was a
1001 * certificate request in which case it is not.
1003 X509_STORE_CTX_set_cert(xsc, x);
1004 X509_STORE_CTX_set_flags(xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
1005 if (!reqfile && X509_verify_cert(xsc) <= 0)
1008 if (!X509_check_private_key(xca, pkey)) {
1010 "CA certificate and CA private key do not match\n");
1014 if (!X509_set_serialNumber(x, bs))
1017 if (!sign(x, pkey, xca, sigopts, days, clrext, digest,
1018 conf, section, preserve_dates))
1023 X509_STORE_CTX_free(xsc);
1025 ERR_print_errors(bio_err);
1027 ASN1_INTEGER_free(bs);
1031 static int callb(int ok, X509_STORE_CTX *ctx)
1037 * It is ok to use a self-signed certificate. This case will catch both
1038 * the initial ok == 0 and the final ok == 1 calls to this function.
1040 err = X509_STORE_CTX_get_error(ctx);
1041 if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1045 * BAD we should have gotten an error. Normally if everything worked
1046 * X509_STORE_CTX_get_error(ctx) will still be set to
1047 * DEPTH_ZERO_SELF_....
1051 "Error with certificate to be certified - should be self-signed\n");
1054 err_cert = X509_STORE_CTX_get_current_cert(ctx);
1055 print_name(bio_err, NULL, X509_get_subject_name(err_cert), 0);
1057 "Error with certificate - error %d at depth %d\n%s\n", err,
1058 X509_STORE_CTX_get_error_depth(ctx),
1059 X509_verify_cert_error_string(err));
1064 static int sign(X509 *x, EVP_PKEY *pkey, X509 *issuer,
1065 STACK_OF(OPENSSL_STRING) *sigopts,
1066 int days, int clrext,
1067 const EVP_MD *digest, CONF *conf, const char *section,
1072 if (!X509_set_issuer_name(x, X509_get_subject_name(issuer)))
1075 if (!preserve_dates && !set_cert_times(x, NULL, NULL, days))
1079 while (X509_get_ext_count(x) > 0)
1080 X509_delete_ext(x, 0);
1083 X509V3_set_ctx(&ext_ctx, issuer, x, NULL, NULL, X509V3_CTX_REPLACE);
1085 /* prepare the correct AKID of self-issued, possibly self-signed cert */
1086 && !X509V3_set_issuer_pkey(&ext_ctx, pkey))
1090 X509V3_set_nconf(&ext_ctx, conf);
1091 if (!X509V3_EXT_add_nconf(conf, &ext_ctx, section, x)) {
1093 "Error adding extensions from section %s\n", section);
1097 return do_X509_sign(x, pkey, digest, sigopts, &ext_ctx);
1100 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1104 id = X509_PURPOSE_get_id(pt);
1105 pname = X509_PURPOSE_get0_name(pt);
1106 for (i = 0; i < 2; i++) {
1107 idret = X509_check_purpose(cert, id, i);
1108 BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
1110 BIO_printf(bio, "Yes\n");
1111 else if (idret == 0)
1112 BIO_printf(bio, "No\n");
1114 BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1119 static int parse_ext_names(char *names, const char **result)
1122 int cnt = 0, len = 0;
1125 len = strlen(names);
1127 while (q - names <= len) {
1128 if (*q != ',' && *q != '\0') {
1134 if (result != NULL) {
1146 static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names)
1148 const STACK_OF(X509_EXTENSION) *exts = NULL;
1149 STACK_OF(X509_EXTENSION) *exts2 = NULL;
1150 X509_EXTENSION *ext = NULL;
1152 int i, j, ret = 0, num, nn = 0;
1153 const char *sn, **names = NULL;
1154 char *tmp_ext_names = NULL;
1156 exts = X509_get0_extensions(x);
1157 if ((num = sk_X509_EXTENSION_num(exts)) <= 0) {
1158 BIO_printf(bio_err, "No extensions in certificate\n");
1163 /* parse comma separated ext name string */
1164 if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL)
1166 if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) {
1167 BIO_printf(bio, "Invalid extension names: %s\n", ext_names);
1170 if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL)
1172 parse_ext_names(tmp_ext_names, names);
1174 for (i = 0; i < num; i++) {
1175 ext = sk_X509_EXTENSION_value(exts, i);
1177 /* check if this ext is what we want */
1178 obj = X509_EXTENSION_get_object(ext);
1179 sn = OBJ_nid2sn(OBJ_obj2nid(obj));
1180 if (sn == NULL || strcmp(sn, "UNDEF") == 0)
1183 for (j = 0; j < nn; j++) {
1184 if (strcmp(sn, names[j]) == 0) {
1185 /* push the extension into a new stack */
1187 && (exts2 = sk_X509_EXTENSION_new_null()) == NULL)
1189 if (!sk_X509_EXTENSION_push(exts2, ext))
1195 if (!sk_X509_EXTENSION_num(exts2)) {
1196 BIO_printf(bio, "No extensions matched with %s\n", ext_names);
1201 ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0);
1203 sk_X509_EXTENSION_free(exts2);
1204 OPENSSL_free(names);
1205 OPENSSL_free(tmp_ext_names);