2 * Copyright 1995-2021 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"
31 #define DEFAULT_DAYS 30 /* default cert validity period in days */
32 #define UNSET_DAYS -2 /* -1 is used for testing expiration checks */
33 #define EXT_COPY_UNSET -1
35 static int callb(int ok, X509_STORE_CTX *ctx);
36 static ASN1_INTEGER *x509_load_serial(const char *CAfile,
37 const char *serialfile, int create);
38 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
39 static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names);
41 typedef enum OPTION_choice {
42 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
43 OPT_INFORM, OPT_OUTFORM, OPT_KEYFORM, OPT_REQ, OPT_CAFORM,
44 OPT_CAKEYFORM, OPT_VFYOPT, OPT_SIGOPT, OPT_DAYS, OPT_PASSIN, OPT_EXTFILE,
45 OPT_EXTENSIONS, OPT_IN, OPT_OUT, OPT_KEY, OPT_SIGNKEY, OPT_CA, OPT_CAKEY,
46 OPT_CASERIAL, OPT_SET_SERIAL, OPT_NEW, OPT_FORCE_PUBKEY, OPT_SUBJ,
47 OPT_ADDTRUST, OPT_ADDREJECT, OPT_SETALIAS, OPT_CERTOPT, OPT_NAMEOPT,
48 OPT_EMAIL, OPT_OCSP_URI, OPT_SERIAL, OPT_NEXT_SERIAL,
49 OPT_MODULUS, OPT_PUBKEY, OPT_X509TOREQ, OPT_TEXT, OPT_HASH,
50 OPT_ISSUER_HASH, OPT_SUBJECT, OPT_ISSUER, OPT_FINGERPRINT, OPT_DATES,
51 OPT_PURPOSE, OPT_STARTDATE, OPT_ENDDATE, OPT_CHECKEND, OPT_CHECKHOST,
52 OPT_CHECKEMAIL, OPT_CHECKIP, OPT_NOOUT, OPT_TRUSTOUT, OPT_CLRTRUST,
53 OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID,
54 OPT_SUBJECT_HASH_OLD, OPT_ISSUER_HASH_OLD, OPT_COPY_EXTENSIONS,
55 OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES,
56 OPT_R_ENUM, OPT_PROV_ENUM, OPT_EXT
59 const OPTIONS x509_options[] = {
60 OPT_SECTION("General"),
61 {"help", OPT_HELP, '-', "Display this summary"},
64 "Certificate input (default stdin), or CSR input file with -req"},
65 {"passin", OPT_PASSIN, 's', "Private key and cert file pass-phrase source"},
66 {"new", OPT_NEW, '-', "Generate a certificate from scratch"},
67 {"x509toreq", OPT_X509TOREQ, '-',
68 "Output a certification request (rather than a certificate)"},
69 {"req", OPT_REQ, '-', "Input is a CSR file (rather than a certificate)"},
70 {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
71 "copy extensions when converting from CSR to x509 or vice versa"},
72 {"inform", OPT_INFORM, 'f',
73 "CSR input file format (DER or PEM) - default PEM"},
74 {"vfyopt", OPT_VFYOPT, 's', "CSR verification parameter in n:v form"},
76 "Key to be used in certificate or cert request"},
77 {"signkey", OPT_SIGNKEY, 's',
79 {"keyform", OPT_KEYFORM, 'E',
80 "Key input format (ENGINE, other values ignored)"},
81 {"out", OPT_OUT, '>', "Output file - default stdout"},
82 {"outform", OPT_OUTFORM, 'f',
83 "Output format (DER or PEM) - default PEM"},
84 {"nocert", OPT_NOCERT, '-',
85 "No cert output (except for requested printing)"},
86 {"noout", OPT_NOOUT, '-', "No output (except for requested printing)"},
88 OPT_SECTION("Certificate printing"),
89 {"text", OPT_TEXT, '-', "Print the certificate in text form"},
90 {"certopt", OPT_CERTOPT, 's', "Various certificate text printing options"},
91 {"fingerprint", OPT_FINGERPRINT, '-', "Print the certificate fingerprint"},
92 {"alias", OPT_ALIAS, '-', "Print certificate alias"},
93 {"serial", OPT_SERIAL, '-', "Print serial number value"},
94 {"startdate", OPT_STARTDATE, '-', "Print the notBefore field"},
95 {"enddate", OPT_ENDDATE, '-', "Print the notAfter field"},
96 {"dates", OPT_DATES, '-', "Print both notBefore and notAfter fields"},
97 {"subject", OPT_SUBJECT, '-', "Print subject DN"},
98 {"issuer", OPT_ISSUER, '-', "Print issuer DN"},
99 {"nameopt", OPT_NAMEOPT, 's',
100 "Certificate subject/issuer name printing options"},
101 {"email", OPT_EMAIL, '-', "Print email address(es)"},
102 {"hash", OPT_HASH, '-', "Synonym for -subject_hash (for backward compat)"},
103 {"subject_hash", OPT_HASH, '-', "Print subject hash value"},
104 #ifndef OPENSSL_NO_MD5
105 {"subject_hash_old", OPT_SUBJECT_HASH_OLD, '-',
106 "Print old-style (MD5) subject hash value"},
108 {"issuer_hash", OPT_ISSUER_HASH, '-', "Print issuer hash value"},
109 #ifndef OPENSSL_NO_MD5
110 {"issuer_hash_old", OPT_ISSUER_HASH_OLD, '-',
111 "Print old-style (MD5) issuer hash value"},
113 {"ext", OPT_EXT, 's',
114 "Restrict which X.509 extensions to print and/or copy"},
115 {"ocspid", OPT_OCSPID, '-',
116 "Print OCSP hash values for the subject name and public key"},
117 {"ocsp_uri", OPT_OCSP_URI, '-', "Print OCSP Responder URL(s)"},
118 {"purpose", OPT_PURPOSE, '-', "Print out certificate purposes"},
119 {"pubkey", OPT_PUBKEY, '-', "Print the public key in PEM format"},
120 {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"},
122 OPT_SECTION("Certificate checking"),
123 {"checkend", OPT_CHECKEND, 'M',
124 "Check whether cert expires in the next arg seconds"},
125 {OPT_MORE_STR, 1, 1, "Exit 1 (failure) if so, 0 if not"},
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"},
130 OPT_SECTION("Certificate output"),
131 {"set_serial", OPT_SET_SERIAL, 's',
132 "Serial number to use, overrides -CAserial"},
133 {"next_serial", OPT_NEXT_SERIAL, '-',
134 "Increment current certificate serial number"},
135 {"days", OPT_DAYS, 'n',
136 "Number of days until newly generated certificate expires - default 30"},
137 {"preserve_dates", OPT_PRESERVE_DATES, '-',
138 "Preserve existing validity dates"},
139 {"subj", OPT_SUBJ, 's', "Set or override certificate subject (and issuer)"},
140 {"force_pubkey", OPT_FORCE_PUBKEY, '<',
141 "Place the given key in new certificate"},
142 {"clrext", OPT_CLREXT, '-',
143 "Do not take over any extensions from the source certificate or request"},
144 {"extfile", OPT_EXTFILE, '<', "Config file with X509V3 extensions to add"},
145 {"extensions", OPT_EXTENSIONS, 's',
146 "Section of extfile to use - default: unnamed section"},
147 {"sigopt", OPT_SIGOPT, 's', "Signature parameter, in n:v form"},
148 {"badsig", OPT_BADSIG, '-',
149 "Corrupt last byte of certificate signature (for test)"},
150 {"", OPT_MD, '-', "Any supported digest, used for signing and printing"},
152 OPT_SECTION("Micro-CA"),
154 "Use the given CA certificate, conflicts with -key"},
155 {"CAform", OPT_CAFORM, 'F', "CA cert format (PEM/DER/P12); has no effect"},
156 {"CAkey", OPT_CAKEY, 's', "The corresponding CA key; default is -CA arg"},
157 {"CAkeyform", OPT_CAKEYFORM, 'E',
158 "CA key format (ENGINE, other values ignored)"},
159 {"CAserial", OPT_CASERIAL, 's',
160 "File that keeps track of CA-generated serial number"},
161 {"CAcreateserial", OPT_CACREATESERIAL, '-',
162 "Create CA serial number file if it does not exist"},
164 OPT_SECTION("Certificate trust output"),
165 {"trustout", OPT_TRUSTOUT, '-', "Mark certificate PEM output as trusted"},
166 {"setalias", OPT_SETALIAS, 's', "Set certificate alias (nickname)"},
167 {"clrtrust", OPT_CLRTRUST, '-', "Clear all trusted purposes"},
168 {"addtrust", OPT_ADDTRUST, 's', "Trust certificate for a given purpose"},
169 {"clrreject", OPT_CLRREJECT, '-',
170 "Clears all the prohibited or rejected uses of the certificate"},
171 {"addreject", OPT_ADDREJECT, 's',
172 "Reject certificate for a given purpose"},
175 #ifndef OPENSSL_NO_ENGINE
176 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
182 static void warn_copying(ASN1_OBJECT *excluded, const char *names)
184 const char *sn = OBJ_nid2sn(OBJ_obj2nid(excluded));
186 if (names != NULL && strstr(names, sn) != NULL)
188 "Warning: -ext should not specify copying %s extension to CSR; ignoring this\n",
192 static X509_REQ *x509_to_req(X509 *cert, EVP_PKEY *pkey, const EVP_MD *digest,
193 STACK_OF(OPENSSL_STRING) *sigopts,
194 int ext_copy, const char *names)
196 const STACK_OF(X509_EXTENSION) *cert_exts = X509_get0_extensions(cert);
197 int i, n = sk_X509_EXTENSION_num(cert_exts /* may be NULL */);
198 ASN1_OBJECT *skid = OBJ_nid2obj(NID_subject_key_identifier);
199 ASN1_OBJECT *akid = OBJ_nid2obj(NID_authority_key_identifier);
200 STACK_OF(X509_EXTENSION) *exts;
201 X509_REQ *req = X509_to_X509_REQ(cert, NULL, NULL);
207 * Filter out SKID and AKID extensions, which make no sense in a CSR.
208 * If names is not NULL, copy only those extensions listed there.
210 warn_copying(skid, names);
211 warn_copying(akid, names);
212 if ((exts = sk_X509_EXTENSION_new_reserve(NULL, n)) == NULL)
214 for (i = 0; i < n; i++) {
215 X509_EXTENSION *ex = sk_X509_EXTENSION_value(cert_exts, i);
216 ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex);
218 if (OBJ_cmp(obj, skid) != 0 && OBJ_cmp(obj, akid) != 0
219 && !sk_X509_EXTENSION_push(exts, ex))
223 if (sk_X509_EXTENSION_num(exts) > 0) {
224 if (ext_copy != EXT_COPY_UNSET && ext_copy != EXT_COPY_NONE
225 && !X509_REQ_add_extensions(req, exts)) {
226 BIO_printf(bio_err, "Error copying extensions from certificate\n");
230 if (!do_X509_REQ_sign(req, pkey, digest, sigopts))
232 sk_X509_EXTENSION_free(exts);
236 sk_X509_EXTENSION_free(exts);
241 int x509_main(int argc, char **argv)
243 ASN1_INTEGER *sno = NULL;
244 ASN1_OBJECT *objtmp = NULL;
246 CONF *extconf = NULL;
247 int ext_copy = EXT_COPY_UNSET;
249 EVP_PKEY *privkey = NULL, *CAkey = NULL, *pubkey = NULL;
252 char *subj = NULL, *digestname = NULL;
253 X509_NAME *fsubj = NULL;
254 const unsigned long chtype = MBSTRING_ASC;
255 const int multirdn = 1;
256 STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
257 STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL;
258 X509 *x = NULL, *xca = NULL, *issuer_cert;
259 X509_REQ *req = NULL, *rq = NULL;
260 X509_STORE *ctx = NULL;
261 const EVP_MD *digest = NULL;
262 char *CAkeyfile = NULL, *CAserial = NULL, *pubkeyfile = NULL, *alias = NULL;
263 char *checkhost = NULL, *checkemail = NULL, *checkip = NULL;
264 char *ext_names = NULL;
265 char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL;
266 char *infile = NULL, *outfile = NULL, *privkeyfile = NULL, *CAfile = NULL;
268 int days = UNSET_DAYS; /* not explicitly set */
269 int x509toreq = 0, modulus = 0, print_pubkey = 0, pprint = 0;
270 int CAformat = FORMAT_PEM, CAkeyformat = FORMAT_PEM;
271 int fingerprint = 0, reqfile = 0, checkend = 0;
272 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyformat = FORMAT_PEM;
273 int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0;
274 int noout = 0, CA_createserial = 0, email = 0;
275 int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0;
276 int ret = 1, i, j, num = 0, badsig = 0, clrext = 0, nocert = 0;
277 int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0;
279 time_t checkoffset = 0;
280 unsigned long certflag = 0;
281 int preserve_dates = 0;
284 #ifndef OPENSSL_NO_MD5
285 int subject_hash_old = 0, issuer_hash_old = 0;
288 ctx = X509_STORE_new();
291 X509_STORE_set_verify_cb(ctx, callb);
293 prog = opt_init(argc, argv, x509_options);
294 while ((o = opt_next()) != OPT_EOF) {
299 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
302 opt_help(x509_options);
306 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
313 if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
317 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
321 if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAformat))
325 if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAkeyformat))
334 case OPT_COPY_EXTENSIONS:
335 if (!set_ext_copy(&ext_copy, opt_arg())) {
337 "Invalid extension copy option: %s\n", opt_arg());
344 sigopts = sk_OPENSSL_STRING_new_null();
345 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
350 vfyopts = sk_OPENSSL_STRING_new_null();
351 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
355 days = atoi(opt_arg());
357 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
363 passinarg = opt_arg();
373 if (!opt_provider(o))
381 privkeyfile = opt_arg();
387 CAkeyfile = opt_arg();
390 CAserial = opt_arg();
394 BIO_printf(bio_err, "Serial number supplied twice\n");
397 if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL)
403 case OPT_FORCE_PUBKEY:
404 pubkeyfile = opt_arg();
410 if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL)
412 if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
413 BIO_printf(bio_err, "%s: Invalid trust object value %s\n",
417 sk_ASN1_OBJECT_push(trust, objtmp);
421 if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL)
423 if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
424 BIO_printf(bio_err, "%s: Invalid reject object value %s\n",
428 sk_ASN1_OBJECT_push(reject, objtmp);
436 if (!set_cert_ex(&certflag, opt_arg()))
440 if (!set_nameopt(opt_arg()))
444 e = setup_engine(opt_arg(), 0);
455 case OPT_NEXT_SERIAL:
462 print_pubkey = ++num;
476 case OPT_FINGERPRINT:
480 subject_hash = ++num;
482 case OPT_ISSUER_HASH:
499 ext_names = opt_arg();
516 case OPT_CACREATESERIAL:
517 CA_createserial = ++num;
528 #ifndef OPENSSL_NO_MD5
529 case OPT_SUBJECT_HASH_OLD:
530 subject_hash_old = ++num;
532 case OPT_ISSUER_HASH_OLD:
533 issuer_hash_old = ++num;
536 case OPT_SUBJECT_HASH_OLD:
537 case OPT_ISSUER_HASH_OLD:
548 if (!opt_imax(opt_arg(), &temp))
550 checkoffset = (time_t)temp;
551 if ((intmax_t)checkoffset != temp) {
552 BIO_printf(bio_err, "%s: Checkend time out of range %s\n",
559 checkhost = opt_arg();
562 checkemail = opt_arg();
567 case OPT_PRESERVE_DATES:
571 digestname = opt_unknown();
576 /* No extra arguments. */
577 argc = opt_num_rest();
582 if (digestname != NULL) {
583 if (!opt_md(digestname, &digest))
586 if (preserve_dates && days != UNSET_DAYS) {
587 BIO_printf(bio_err, "Cannot use -preserve_dates with -days option\n");
590 if (days == UNSET_DAYS)
593 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
594 BIO_printf(bio_err, "Error getting password\n");
598 if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(),
602 if (newcert && infile != NULL) {
603 BIO_printf(bio_err, "The -in option cannot be used with -new\n");
606 if (newcert && reqfile) {
608 "The -req option cannot be used with -new\n");
611 if (privkeyfile != NULL) {
612 privkey = load_key(privkeyfile, keyformat, 0, passin, e, "private key");
616 if (pubkeyfile != NULL) {
617 if ((pubkey = load_pubkey(pubkeyfile, keyformat, 0, NULL, e,
618 "explicitly set public key")) == NULL)
625 "The -new option requires a subject to be set using -subj\n");
628 if (privkeyfile == NULL && pubkeyfile == NULL) {
630 "The -new option without -key requires using -force_pubkey\n");
635 && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
638 if (CAkeyfile == NULL)
640 if (CAfile != NULL) {
641 if (privkeyfile != NULL) {
642 BIO_printf(bio_err, "Cannot use both -key and -CA option\n");
645 } else if (CAkeyfile != NULL) {
647 "Warning: ignoring -CAkey option since no -CA option is given\n");
650 if (extfile == NULL) {
653 "Warning: ignoring -extensions option without -extfile\n");
657 if ((extconf = app_load_config(extfile)) == NULL)
659 if (extsect == NULL) {
660 extsect = NCONF_get_string(extconf, "default", "extensions");
661 if (extsect == NULL) {
666 X509V3_set_ctx_test(&ctx2);
667 X509V3_set_nconf(&ctx2, extconf);
668 if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
670 "Error checking extension section %s\n", extsect);
676 req = load_csr(infile, informat, "certificate request input");
680 if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) {
681 BIO_printf(bio_err, "Error unpacking public key from CSR\n");
684 i = do_X509_REQ_verify(req, pkey, vfyopts);
686 BIO_printf(bio_err, i < 0
687 ? "Error while verifying certificate request self-signature\n"
688 : "Certificate request self-signature did not match the contents\n");
691 BIO_printf(out, "Certificate request self-signature ok\n");
693 print_name(out, "subject=", X509_REQ_get_subject_name(req));
694 } else if (!x509toreq && ext_copy != EXT_COPY_UNSET) {
695 BIO_printf(bio_err, "Warning: ignoring -copy_extensions since neither -x509toreq nor -req is given\n");
698 if (reqfile || newcert) {
701 "Warning: ignoring -preserve_dates option with -req or -new\n");
703 if (privkeyfile == NULL && CAkeyfile == NULL) {
705 "We need a private key to sign with, use -key or -CAkey or -CA with private key\n");
708 if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
711 sno = ASN1_INTEGER_new();
712 if (sno == NULL || !rand_serial(NULL, sno))
715 if (req != NULL && ext_copy != EXT_COPY_UNSET) {
716 if (clrext && ext_copy != EXT_COPY_NONE) {
717 BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
719 } else if (!copy_extensions(x, req, ext_copy)) {
720 BIO_printf(bio_err, "Error copying extensions from request\n");
725 x = load_cert_pass(infile, 1, passin, "certificate");
729 if ((fsubj != NULL || req != NULL)
730 && !X509_set_subject_name(x, fsubj != NULL ? fsubj :
731 X509_REQ_get_subject_name(req)))
733 if ((pubkey != NULL || privkey != NULL || req != NULL)
734 && !X509_set_pubkey(x, pubkey != NULL ? pubkey :
735 privkey != NULL ? privkey :
736 X509_REQ_get0_pubkey(req)))
739 if (CAfile != NULL) {
740 xca = load_cert_pass(CAfile, 1, passin, "CA certificate");
745 out = bio_open_default(outfile, 'w', outformat);
749 if (!noout || text || next_serial)
750 OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3");
751 /* TODO: why is this strange object created (and no error checked)? */
754 X509_alias_set1(x, (unsigned char *)alias, -1);
759 X509_reject_clear(x);
762 for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++)
763 X509_add1_trust_object(x, sk_ASN1_OBJECT_value(trust, i));
766 if (reject != NULL) {
767 for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++)
768 X509_add1_reject_object(x, sk_ASN1_OBJECT_value(reject, i));
771 if (clrext && ext_names != NULL)
772 BIO_printf(bio_err, "Warning: Ignoring -ext since -clrext is given\n");
773 for (i = X509_get_ext_count(x) - 1; i >= 0; i--) {
774 X509_EXTENSION *ex = X509_get_ext(x, i);
775 const char *sn = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ex)));
777 if (clrext || (ext_names != NULL && strstr(ext_names, sn) == NULL))
778 X509_EXTENSION_free(X509_delete_ext(x, i));
782 if (CAfile != NULL) {
785 sno = x509_load_serial(CAfile, CAserial, CA_createserial);
790 if (sno != NULL && !X509_set_serialNumber(x, sno))
793 if (reqfile || newcert || privkey != NULL || CAfile != NULL) {
794 if (!preserve_dates && !set_cert_times(x, NULL, NULL, days))
796 if (!X509_set_issuer_name(x, X509_get_subject_name(issuer_cert)))
800 X509V3_set_ctx(&ext_ctx, issuer_cert, x, req, NULL, X509V3_CTX_REPLACE);
801 if (extconf != NULL) {
802 X509V3_set_nconf(&ext_ctx, extconf);
803 if (!X509V3_EXT_add_nconf(extconf, &ext_ctx, extsect, x)) {
805 "Error adding extensions from section %s\n", extsect);
810 /* At this point the contents of the certificate x have been finished. */
812 pkey = X509_get0_pubkey(x);
813 if ((print_pubkey != 0 || modulus != 0) && pkey == NULL) {
814 BIO_printf(bio_err, "Error getting public key\n");
818 if (x509toreq) { /* also works in conjunction with -req */
819 if (privkey == NULL) {
820 BIO_printf(bio_err, "Must specify request key using -key\n");
823 if (clrext && ext_copy != EXT_COPY_NONE) {
824 BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n");
827 if ((rq = x509_to_req(x, privkey, digest, sigopts,
828 ext_copy, ext_names)) == NULL)
831 if (outformat == FORMAT_ASN1) {
832 X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT);
833 i = i2d_X509_bio(out, x);
835 i = PEM_write_bio_X509_REQ(out, rq);
839 "Unable to write certificate request\n");
844 } else if (privkey != NULL) {
845 if (!do_X509_sign(x, privkey, digest, sigopts, &ext_ctx))
847 } else if (CAfile != NULL) {
848 if (!reqfile && !newcert) { /* certificate should be self-signed */
849 X509_STORE_CTX *xsc = X509_STORE_CTX_new();
851 if (xsc == NULL || !X509_STORE_CTX_init(xsc, ctx, x, NULL)) {
852 BIO_printf(bio_err, "Error initialising X509 store\n");
853 X509_STORE_CTX_free(xsc);
856 X509_STORE_CTX_set_cert(xsc, x);
857 X509_STORE_CTX_set_flags(xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
858 i = X509_verify_cert(xsc);
859 X509_STORE_CTX_free(xsc);
863 if ((CAkey = load_key(CAkeyfile, CAkeyformat,
864 0, passin, e, "CA private key")) == NULL)
866 if (!X509_check_private_key(xca, CAkey)) {
868 "CA certificate and CA private key do not match\n");
872 if (!do_X509_sign(x, CAkey, digest, sigopts, &ext_ctx))
876 const ASN1_BIT_STRING *signature;
878 X509_get0_signature(&signature, NULL, x);
879 corrupt_signature(signature);
882 /* Process print options in the given order, as indicated by index i */
883 for (i = 1; i <= num; i++) {
885 print_name(out, "issuer=", X509_get_issuer_name(x));
886 } else if (i == subject) {
887 print_name(out, "subject=", X509_get_subject_name(x));
888 } else if (i == serial) {
889 BIO_printf(out, "serial=");
890 i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x));
891 BIO_printf(out, "\n");
892 } else if (i == next_serial) {
894 BIGNUM *bnser = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x), NULL);
898 if (!BN_add_word(bnser, 1)
899 || (ser = BN_to_ASN1_INTEGER(bnser, NULL)) == NULL) {
904 i2a_ASN1_INTEGER(out, ser);
905 ASN1_INTEGER_free(ser);
907 } else if (i == email || i == ocsp_uri) {
908 STACK_OF(OPENSSL_STRING) *emlst =
909 i == email ? X509_get1_email(x) : X509_get1_ocsp(x);
911 for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
912 BIO_printf(out, "%s\n", sk_OPENSSL_STRING_value(emlst, j));
913 X509_email_free(emlst);
914 } else if (i == aliasout) {
915 unsigned char *alstr = X509_alias_get0(x, NULL);
918 BIO_printf(out, "%s\n", alstr);
920 BIO_puts(out, "<No Alias>\n");
921 } else if (i == subject_hash) {
922 BIO_printf(out, "%08lx\n", X509_subject_name_hash(x));
923 #ifndef OPENSSL_NO_MD5
924 } else if (i == subject_hash_old) {
925 BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x));
927 } else if (i == issuer_hash) {
928 BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x));
929 #ifndef OPENSSL_NO_MD5
930 } else if (i == issuer_hash_old) {
931 BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x));
933 } else if (i == pprint) {
934 BIO_printf(out, "Certificate purposes:\n");
935 for (j = 0; j < X509_PURPOSE_get_count(); j++)
936 purpose_print(out, x, X509_PURPOSE_get0(j));
937 } else if (i == modulus) {
938 BIO_printf(out, "Modulus=");
939 if (EVP_PKEY_is_a(pkey, "RSA")) {
942 /* Every RSA key has an 'n' */
943 EVP_PKEY_get_bn_param(pkey, "n", &n);
946 } else if (EVP_PKEY_is_a(pkey, "DSA")) {
949 /* Every DSA key has a 'pub' */
950 EVP_PKEY_get_bn_param(pkey, "pub", &dsapub);
951 BN_print(out, dsapub);
954 BIO_printf(out, "No modulus for this public key type");
956 BIO_printf(out, "\n");
957 } else if (i == print_pubkey) {
958 PEM_write_bio_PUBKEY(out, pkey);
959 } else if (i == text) {
960 X509_print_ex(out, x, get_nameopt(), certflag);
961 } else if (i == startdate) {
962 BIO_puts(out, "notBefore=");
963 ASN1_TIME_print(out, X509_get0_notBefore(x));
965 } else if (i == enddate) {
966 BIO_puts(out, "notAfter=");
967 ASN1_TIME_print(out, X509_get0_notAfter(x));
969 } else if (i == fingerprint) {
971 unsigned char md[EVP_MAX_MD_SIZE];
972 const EVP_MD *fdig = digest;
977 if (!X509_digest(x, fdig, md, &n)) {
978 BIO_printf(bio_err, "Out of memory\n");
981 BIO_printf(out, "%s Fingerprint=", EVP_MD_name(fdig));
982 for (j = 0; j < (int)n; j++)
983 BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':');
984 } else if (i == ocspid) {
985 X509_ocspid_print(out, x);
986 } else if (i == ext) {
987 print_x509v3_exts(out, x, ext_names);
992 time_t tcheck = time(NULL) + checkoffset;
994 ret = X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0;
996 BIO_printf(out, "Certificate will expire\n");
998 BIO_printf(out, "Certificate will not expire\n");
1002 print_cert_checks(out, x, checkhost, checkemail, checkip);
1004 if (noout || nocert) {
1009 if (outformat == FORMAT_ASN1) {
1010 i = i2d_X509_bio(out, x);
1011 } else if (outformat == FORMAT_PEM) {
1013 i = PEM_write_bio_X509_AUX(out, x);
1015 i = PEM_write_bio_X509(out, x);
1017 BIO_printf(bio_err, "Bad output format specified for outfile\n");
1021 BIO_printf(bio_err, "Unable to write certificate\n");
1028 ERR_print_errors(bio_err);
1029 NCONF_free(extconf);
1031 X509_STORE_free(ctx);
1032 X509_NAME_free(fsubj);
1036 EVP_PKEY_free(privkey);
1037 EVP_PKEY_free(CAkey);
1038 EVP_PKEY_free(pubkey);
1039 sk_OPENSSL_STRING_free(sigopts);
1040 sk_OPENSSL_STRING_free(vfyopts);
1042 ASN1_INTEGER_free(sno);
1043 sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
1044 sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
1050 static ASN1_INTEGER *x509_load_serial(const char *CAfile,
1051 const char *serialfile, int create)
1054 ASN1_INTEGER *bs = NULL;
1055 BIGNUM *serial = NULL;
1057 if (serialfile == NULL) {
1058 const char *p = strrchr(CAfile, '.');
1059 size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile);
1061 buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer");
1062 memcpy(buf, CAfile, len);
1063 memcpy(buf + len, POSTFIX, sizeof(POSTFIX));
1067 serial = load_serial(serialfile, create, NULL);
1071 if (!BN_add_word(serial, 1)) {
1072 BIO_printf(bio_err, "Serial number increment failure\n");
1076 if (!save_serial(serialfile, NULL, serial, &bs))
1085 static int callb(int ok, X509_STORE_CTX *ctx)
1091 * It is ok to use a self-signed certificate. This case will catch both
1092 * the initial ok == 0 and the final ok == 1 calls to this function.
1094 err = X509_STORE_CTX_get_error(ctx);
1095 if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1099 * BAD we should have gotten an error. Normally if everything worked
1100 * X509_STORE_CTX_get_error(ctx) will still be set to
1101 * DEPTH_ZERO_SELF_....
1105 "Error with certificate to be certified - should be self-signed\n");
1108 err_cert = X509_STORE_CTX_get_current_cert(ctx);
1109 print_name(bio_err, "subject=", X509_get_subject_name(err_cert));
1111 "Error with certificate - error %d at depth %d\n%s\n", err,
1112 X509_STORE_CTX_get_error_depth(ctx),
1113 X509_verify_cert_error_string(err));
1118 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1122 id = X509_PURPOSE_get_id(pt);
1123 pname = X509_PURPOSE_get0_name(pt);
1124 for (i = 0; i < 2; i++) {
1125 idret = X509_check_purpose(cert, id, i);
1126 BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
1128 BIO_printf(bio, "Yes\n");
1129 else if (idret == 0)
1130 BIO_printf(bio, "No\n");
1132 BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1137 static int parse_ext_names(char *names, const char **result)
1140 int cnt = 0, len = 0;
1143 len = strlen(names);
1145 while (q - names <= len) {
1146 if (*q != ',' && *q != '\0') {
1152 if (result != NULL) {
1164 static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names)
1166 const STACK_OF(X509_EXTENSION) *exts = NULL;
1167 STACK_OF(X509_EXTENSION) *exts2 = NULL;
1168 X509_EXTENSION *ext = NULL;
1170 int i, j, ret = 0, num, nn = 0;
1171 const char *sn, **names = NULL;
1172 char *tmp_ext_names = NULL;
1174 exts = X509_get0_extensions(x);
1175 if ((num = sk_X509_EXTENSION_num(exts)) <= 0) {
1176 BIO_printf(bio_err, "No extensions in certificate\n");
1181 /* parse comma separated ext name string */
1182 if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL)
1184 if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) {
1185 BIO_printf(bio, "Invalid extension names: %s\n", ext_names);
1188 if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL)
1190 parse_ext_names(tmp_ext_names, names);
1192 for (i = 0; i < num; i++) {
1193 ext = sk_X509_EXTENSION_value(exts, i);
1195 /* check if this ext is what we want */
1196 obj = X509_EXTENSION_get_object(ext);
1197 sn = OBJ_nid2sn(OBJ_obj2nid(obj));
1198 if (sn == NULL || strcmp(sn, "UNDEF") == 0)
1201 for (j = 0; j < nn; j++) {
1202 if (strcmp(sn, names[j]) == 0) {
1203 /* push the extension into a new stack */
1205 && (exts2 = sk_X509_EXTENSION_new_null()) == NULL)
1207 if (!sk_X509_EXTENSION_push(exts2, ext))
1213 if (!sk_X509_EXTENSION_num(exts2)) {
1214 BIO_printf(bio, "No extensions matched with %s\n", ext_names);
1219 ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0);
1221 sk_X509_EXTENSION_free(exts2);
1222 OPENSSL_free(names);
1223 OPENSSL_free(tmp_ext_names);