2 * Copyright 2001-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
10 #include <openssl/opensslconf.h>
12 #ifdef OPENSSL_SYS_VMS
13 /* So fd_set and friends get properly defined on OpenVMS */
14 # define _XOPEN_SOURCE_EXTENDED
23 /* Needs to be included before the openssl headers */
26 #include "internal/sockets.h"
27 #include <openssl/e_os2.h>
28 #include <openssl/crypto.h>
29 #include <openssl/err.h>
30 #include <openssl/ssl.h>
31 #include <openssl/evp.h>
32 #include <openssl/bn.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/rand.h>
36 DEFINE_STACK_OF(OCSP_CERTID)
37 DEFINE_STACK_OF(CONF_VALUE)
39 DEFINE_STACK_OF_STRING()
42 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
55 #if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
56 && !defined(OPENSSL_NO_POSIX_IO)
58 # include <sys/types.h>
59 # include <sys/wait.h>
62 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
68 # define LOG_WARNING 1
72 #if defined(OPENSSL_SYS_VXWORKS)
74 int setpgid(pid_t pid, pid_t pgid)
86 /* Maximum leeway in validity period: default 5 minutes */
87 #define MAX_VALIDITY_PERIOD (5 * 60)
89 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
90 const EVP_MD *cert_id_md, X509 *issuer,
91 STACK_OF(OCSP_CERTID) *ids);
92 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
93 const EVP_MD *cert_id_md, X509 *issuer,
94 STACK_OF(OCSP_CERTID) *ids);
95 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
96 STACK_OF(OPENSSL_STRING) *names,
97 STACK_OF(OCSP_CERTID) *ids, long nsec,
99 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
100 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
101 EVP_PKEY *rkey, const EVP_MD *md,
102 STACK_OF(OPENSSL_STRING) *sigopts,
103 STACK_OF(X509) *rother, unsigned long flags,
104 int nmin, int ndays, int badsig,
105 const EVP_MD *resp_md);
107 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
108 static BIO *init_responder(const char *port);
109 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
110 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
111 static void log_message(int level, const char *fmt, ...);
113 static int multi = 0;
116 static int acfd = (int) INVALID_SOCKET;
117 static int index_changed(CA_DB *);
118 static void spawn_loop(void);
119 static int print_syslog(const char *str, size_t len, void *levPtr);
120 static void socket_timeout(int signum);
123 typedef enum OPTION_choice {
124 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
125 OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
126 OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
127 OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
128 OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
129 OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
130 OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
131 OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
132 OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE,
133 OPT_NOCAPATH, OPT_NOCASTORE,
134 OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
135 OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
136 OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
137 OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
142 OPT_MULTI, OPT_PROV_ENUM
145 const OPTIONS ocsp_options[] = {
146 OPT_SECTION("General"),
147 {"help", OPT_HELP, '-', "Display this summary"},
148 {"ignore_err", OPT_IGNORE_ERR, '-',
149 "Ignore error on OCSP request or response and continue running"},
150 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
151 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
152 {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
153 {"no-CAfile", OPT_NOCAFILE, '-',
154 "Do not load the default certificates file"},
155 {"no-CApath", OPT_NOCAPATH, '-',
156 "Do not load certificates from the default certificates directory"},
157 {"no-CAstore", OPT_NOCAPATH, '-',
158 "Do not load certificates from the default certificates store"},
160 OPT_SECTION("Responder"),
161 {"timeout", OPT_TIMEOUT, 'p',
162 "Connection timeout (in seconds) to the OCSP responder"},
163 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
164 "Don't include any certificates in response"},
166 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
168 {"no_certs", OPT_NO_CERTS, '-',
169 "Don't include any certificates in signed request"},
170 {"badsig", OPT_BADSIG, '-',
171 "Corrupt last byte of loaded OSCP response signature (for test)"},
172 {"CA", OPT_CA, '<', "CA certificate"},
173 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
174 {"nrequest", OPT_REQUEST, 'p',
175 "Number of requests to accept (default unlimited)"},
176 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
177 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
178 {"sign_other", OPT_SIGN_OTHER, '<',
179 "Additional certificates to include in signed request"},
180 {"index", OPT_INDEX, '<', "Certificate status index file"},
181 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
182 {"rsigner", OPT_RSIGNER, '<',
183 "Responder certificate to sign responses with"},
184 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
185 {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"},
186 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
187 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
188 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
189 {"header", OPT_HEADER, 's', "key=value header to add"},
190 {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
191 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
193 OPT_SECTION("Client"),
194 {"url", OPT_URL, 's', "Responder URL"},
195 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
196 {"port", OPT_PORT, 'p', "Port to run responder on"},
197 {"out", OPT_OUTFILE, '>', "Output filename"},
198 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
199 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
200 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
201 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
202 "Don't check signature on response"},
203 {"resp_key_id", OPT_RESP_KEY_ID, '-',
204 "Identify response by signing certificate key ID"},
205 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
206 "Don't check signing certificate"},
207 {"text", OPT_TEXT, '-', "Print text form of request and response"},
208 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
209 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
210 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
211 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
212 "Don't do additional checks on signing certificate"},
213 {"no_explicit", OPT_NO_EXPLICIT, '-',
214 "Do not explicitly check the chain, just verify the root"},
215 {"trust_other", OPT_TRUST_OTHER, '-',
216 "Don't verify additional certificates"},
217 {"no_intern", OPT_NO_INTERN, '-',
218 "Don't search certificates contained in response for signer"},
219 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
220 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
221 {"verify_other", OPT_VERIFY_OTHER, '<',
222 "Additional certificates to search for signer"},
223 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
224 {"cert", OPT_CERT, '<', "Certificate to check"},
225 {"serial", OPT_SERIAL, 's', "Serial number to check"},
226 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
227 "Maximum validity discrepancy in seconds"},
228 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
229 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
230 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
231 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
232 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
239 int ocsp_main(int argc, char **argv)
241 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
242 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
243 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
246 EVP_PKEY *key = NULL, *rkey = NULL;
247 OCSP_BASICRESP *bs = NULL;
248 OCSP_REQUEST *req = NULL;
249 OCSP_RESPONSE *resp = NULL;
250 STACK_OF(CONF_VALUE) *headers = NULL;
251 STACK_OF(OCSP_CERTID) *ids = NULL;
252 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
253 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
254 STACK_OF(X509) *issuers = NULL;
255 X509 *issuer = NULL, *cert = NULL;
256 STACK_OF(X509) *rca_cert = NULL;
257 const EVP_MD *resp_certid_md = NULL;
258 X509 *signer = NULL, *rsigner = NULL;
259 X509_STORE *store = NULL;
260 X509_VERIFY_PARAM *vpm = NULL;
261 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
262 char *header, *value;
263 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
264 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
265 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
266 char *rsignfile = NULL, *rkeyfile = NULL;
267 char *passinarg = NULL, *passin = NULL;
268 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
269 char *signfile = NULL, *keyfile = NULL;
270 char *thost = NULL, *tport = NULL, *tpath = NULL;
271 int noCAfile = 0, noCApath = 0, noCAstore = 0;
272 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
273 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
274 int req_text = 0, resp_text = 0, ret = 1;
275 int req_timeout = -1;
276 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
277 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
280 reqnames = sk_OPENSSL_STRING_new_null();
281 if (reqnames == NULL)
283 ids = sk_OCSP_CERTID_new_null();
286 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
289 prog = opt_init(argc, argv, ocsp_options);
290 while ((o = opt_next()) != OPT_EOF) {
295 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
299 opt_help(ocsp_options);
305 #ifndef OPENSSL_NO_SOCK
306 req_timeout = atoi(opt_arg());
313 thost = tport = tpath = NULL;
314 if (!OSSL_HTTP_parse_url(opt_arg(),
315 &host, &port, &path, &use_ssl)) {
316 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
341 case OPT_RESP_NO_CERTS:
342 rflags |= OCSP_NOCERTS;
344 case OPT_RESP_KEY_ID:
345 rflags |= OCSP_RESPID_KEY;
348 sign_flags |= OCSP_NOCERTS;
350 case OPT_NO_SIGNATURE_VERIFY:
351 verify_flags |= OCSP_NOSIGS;
353 case OPT_NO_CERT_VERIFY:
354 verify_flags |= OCSP_NOVERIFY;
357 verify_flags |= OCSP_NOCHAIN;
359 case OPT_NO_CERT_CHECKS:
360 verify_flags |= OCSP_NOCHECKS;
362 case OPT_NO_EXPLICIT:
363 verify_flags |= OCSP_NOEXPLICIT;
365 case OPT_TRUST_OTHER:
366 verify_flags |= OCSP_TRUSTOTHER;
369 verify_flags |= OCSP_NOINTERN;
375 req_text = resp_text = 1;
390 signfile = opt_arg();
393 verify_certfile = opt_arg();
394 verify_flags |= OCSP_TRUSTOTHER;
397 sign_certfile = opt_arg();
399 case OPT_VERIFY_OTHER:
400 verify_certfile = opt_arg();
421 if (!opt_verify(o, vpm))
425 case OPT_VALIDITY_PERIOD:
426 opt_long(opt_arg(), &nsec);
429 opt_long(opt_arg(), &maxage);
444 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
447 if (issuers == NULL) {
448 if ((issuers = sk_X509_new_null()) == NULL)
451 if (!sk_X509_push(issuers, issuer))
456 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
459 if (cert_id_md == NULL)
460 cert_id_md = EVP_sha1();
461 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
463 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
468 if (cert_id_md == NULL)
469 cert_id_md = EVP_sha1();
470 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
472 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
477 ridx_filename = opt_arg();
480 rca_filename = opt_arg();
483 opt_int(opt_arg(), &nmin);
488 opt_int(opt_arg(), &accept_count);
491 ndays = atoi(opt_arg());
494 rsignfile = opt_arg();
497 rkeyfile = opt_arg();
500 passinarg = opt_arg();
503 rcertfile = opt_arg();
505 case OPT_RMD: /* Response MessageDigest */
506 if (!opt_md(opt_arg(), &rsign_md))
510 if (rsign_sigopts == NULL)
511 rsign_sigopts = sk_OPENSSL_STRING_new_null();
512 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
517 value = strchr(header, '=');
519 BIO_printf(bio_err, "Missing = in header key=value\n");
523 if (!X509V3_add_value(header, value, &headers))
527 resp_certid_md = EVP_get_digestbyname(opt_arg());
528 if (resp_certid_md == NULL)
534 "%s: Digest must be before -cert or -serial\n",
538 if (!opt_md(opt_unknown(), &cert_id_md))
544 multi = atoi(opt_arg());
548 if (!opt_provider(o))
554 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
558 argc = opt_num_rest();
562 /* Have we anything to do? */
563 if (req == NULL && reqin == NULL
564 && respin == NULL && !(port != NULL && ridx_filename != NULL))
567 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
571 if (req == NULL && (add_nonce != 2))
574 if (req == NULL && reqin != NULL) {
575 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
578 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
581 BIO_printf(bio_err, "Error reading OCSP request\n");
586 if (req == NULL && port != NULL) {
587 acbio = init_responder(port);
592 if (rsignfile != NULL) {
593 if (rkeyfile == NULL)
594 rkeyfile = rsignfile;
595 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
596 if (rsigner == NULL) {
597 BIO_printf(bio_err, "Error loading responder certificate\n");
600 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
601 NULL, "CA certificate"))
603 if (rcertfile != NULL) {
604 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
605 "responder other certificates"))
608 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
609 BIO_printf(bio_err, "Error getting password\n");
612 rkey = load_key(rkeyfile, FORMAT_PEM, 0, passin, NULL,
613 "responder private key");
618 if (ridx_filename != NULL
619 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
621 "Responder mode requires certificate, key, and CA.\n");
625 if (ridx_filename != NULL) {
626 rdb = load_index(ridx_filename, NULL);
627 if (rdb == NULL || index_index(rdb) <= 0) {
634 if (multi && acbio != NULL)
636 if (acbio != NULL && req_timeout > 0)
637 signal(SIGALRM, socket_timeout);
641 log_message(LOG_INFO, "waiting for OCSP client connections...");
647 if (index_changed(rdb)) {
648 CA_DB *newrdb = load_index(ridx_filename, NULL);
650 if (newrdb != NULL && index_index(newrdb) > 0) {
655 log_message(LOG_ERR, "error reloading updated index: %s",
662 if (!do_responder(&req, &cbio, acbio, req_timeout))
667 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
669 send_ocsp_response(cbio, resp);
675 && (signfile != NULL || reqout != NULL
676 || host != NULL || add_nonce || ridx_filename != NULL)) {
677 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
681 if (req != NULL && add_nonce) {
682 if (!OCSP_request_add1_nonce(req, NULL, -1))
686 if (signfile != NULL) {
689 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
690 if (signer == NULL) {
691 BIO_printf(bio_err, "Error loading signer certificate\n");
694 if (sign_certfile != NULL) {
695 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
696 "signer certificates"))
699 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
700 "signer private key");
704 if (!OCSP_request_sign
705 (req, signer, key, NULL, sign_other, sign_flags)) {
706 BIO_printf(bio_err, "Error signing OCSP request\n");
711 if (req_text && req != NULL)
712 OCSP_REQUEST_print(out, req, 0);
714 if (reqout != NULL) {
715 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
718 i2d_OCSP_REQUEST_bio(derbio, req);
723 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
724 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
727 send_ocsp_response(cbio, resp);
728 } else if (host != NULL) {
729 #ifndef OPENSSL_NO_SOCK
730 resp = process_responder(req, host, path,
731 port, use_ssl, headers, req_timeout);
736 "Error creating connect BIO - sockets not supported.\n");
739 } else if (respin != NULL) {
740 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
743 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
746 BIO_printf(bio_err, "Error reading OCSP response\n");
756 if (respout != NULL) {
757 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
760 i2d_OCSP_RESPONSE_bio(derbio, resp);
764 i = OCSP_response_status(resp);
765 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
766 BIO_printf(out, "Responder Error: %s (%d)\n",
767 OCSP_response_status_str(i), i);
773 OCSP_RESPONSE_print(out, resp, 0);
775 /* If running as responder don't verify our own response */
777 /* If not unlimited, see if we took all we should. */
778 if (accept_count != -1 && --accept_count <= 0) {
784 OCSP_REQUEST_free(req);
786 OCSP_RESPONSE_free(resp);
790 if (ridx_filename != NULL) {
796 store = setup_verify(CAfile, noCAfile, CApath, noCApath,
802 X509_STORE_set1_param(store, vpm);
803 if (verify_certfile != NULL) {
804 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
805 "validator certificate"))
809 bs = OCSP_response_get1_basic(resp);
811 BIO_printf(bio_err, "Error parsing response\n");
818 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
820 BIO_printf(bio_err, "WARNING: no nonce in response\n");
822 BIO_printf(bio_err, "Nonce Verify error\n");
828 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
829 if (i <= 0 && issuers) {
830 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
835 BIO_printf(bio_err, "Response Verify Failure\n");
836 ERR_print_errors(bio_err);
839 BIO_printf(bio_err, "Response verify OK\n");
843 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
846 ERR_print_errors(bio_err);
848 X509_STORE_free(store);
849 X509_VERIFY_PARAM_free(vpm);
850 sk_OPENSSL_STRING_free(rsign_sigopts);
854 sk_X509_pop_free(issuers, X509_free);
856 sk_X509_pop_free(rca_cert, X509_free);
861 OCSP_REQUEST_free(req);
862 OCSP_RESPONSE_free(resp);
863 OCSP_BASICRESP_free(bs);
864 sk_OPENSSL_STRING_free(reqnames);
865 sk_OCSP_CERTID_free(ids);
866 sk_X509_pop_free(sign_other, X509_free);
867 sk_X509_pop_free(verify_other, X509_free);
868 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
877 log_message(int level, const char *fmt, ...)
885 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
886 syslog(level, "%s", buf);
888 if (level >= LOG_ERR)
889 ERR_print_errors_cb(print_syslog, &level);
893 BIO_printf(bio_err, "%s: ", prog);
894 BIO_vprintf(bio_err, fmt, ap);
895 BIO_printf(bio_err, "\n");
902 static int print_syslog(const char *str, size_t len, void *levPtr)
904 int level = *(int *)levPtr;
905 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
907 syslog(level, "%.*s", ilen, str);
912 static int index_changed(CA_DB *rdb)
916 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
917 if (rdb->dbst.st_mtime != sb.st_mtime
918 || rdb->dbst.st_ctime != sb.st_ctime
919 || rdb->dbst.st_ino != sb.st_ino
920 || rdb->dbst.st_dev != sb.st_dev) {
921 syslog(LOG_INFO, "index file changed, reloading");
928 static void killall(int ret, pid_t *kidpids)
932 for (i = 0; i < multi; ++i)
934 (void)kill(kidpids[i], SIGTERM);
935 OPENSSL_free(kidpids);
940 static int termsig = 0;
942 static void noteterm (int sig)
948 * Loop spawning up to `multi` child processes, only child processes return
949 * from this function. The parent process loops until receiving a termination
950 * signal, kills extant children and exits without returning.
952 static void spawn_loop(void)
954 pid_t *kidpids = NULL;
959 openlog(prog, LOG_PID, LOG_DAEMON);
962 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
966 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
967 for (i = 0; i < multi; ++i)
970 signal(SIGINT, noteterm);
971 signal(SIGTERM, noteterm);
973 while (termsig == 0) {
977 * Wait for a child to replace when we're at the limit.
978 * Slow down if a child exited abnormally or waitpid() < 0
980 while (termsig == 0 && procs >= multi) {
981 if ((fpid = waitpid(-1, &status, 0)) > 0) {
982 for (i = 0; i < procs; ++i) {
983 if (kidpids[i] == fpid) {
990 syslog(LOG_ERR, "fatal: internal error: "
991 "no matching child slot for pid: %ld",
996 if (WIFEXITED(status))
997 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
998 (long)fpid, WEXITSTATUS(status));
999 else if (WIFSIGNALED(status))
1000 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
1001 (long)fpid, WTERMSIG(status),
1003 WCOREDUMP(status) ? " (core dumped)" :
1009 } else if (errno != EINTR) {
1010 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
1011 killall(1, kidpids);
1017 switch(fpid = fork()) {
1018 case -1: /* error */
1019 /* System critically low on memory, pause and try again later */
1023 OPENSSL_free(kidpids);
1024 signal(SIGINT, SIG_DFL);
1025 signal(SIGTERM, SIG_DFL);
1028 if (RAND_poll() <= 0) {
1029 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1033 default: /* parent */
1034 for (i = 0; i < multi; ++i) {
1035 if (kidpids[i] == 0) {
1042 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1043 killall(1, kidpids);
1049 /* The loop above can only break on termsig */
1050 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1051 killall(0, kidpids);
1055 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1056 const EVP_MD *cert_id_md, X509 *issuer,
1057 STACK_OF(OCSP_CERTID) *ids)
1061 if (issuer == NULL) {
1062 BIO_printf(bio_err, "No issuer certificate specified\n");
1066 *req = OCSP_REQUEST_new();
1069 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1070 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1072 if (!OCSP_request_add0_id(*req, id))
1077 BIO_printf(bio_err, "Error Creating OCSP request\n");
1081 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1082 const EVP_MD *cert_id_md, X509 *issuer,
1083 STACK_OF(OCSP_CERTID) *ids)
1086 const X509_NAME *iname;
1087 ASN1_BIT_STRING *ikey;
1090 if (issuer == NULL) {
1091 BIO_printf(bio_err, "No issuer certificate specified\n");
1095 *req = OCSP_REQUEST_new();
1098 iname = X509_get_subject_name(issuer);
1099 ikey = X509_get0_pubkey_bitstr(issuer);
1100 sno = s2i_ASN1_INTEGER(NULL, serial);
1102 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1105 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1106 ASN1_INTEGER_free(sno);
1107 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1109 if (!OCSP_request_add0_id(*req, id))
1114 BIO_printf(bio_err, "Error Creating OCSP request\n");
1118 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1119 STACK_OF(OPENSSL_STRING) *names,
1120 STACK_OF(OCSP_CERTID) *ids, long nsec,
1125 int i, status, reason;
1126 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1128 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1129 || !sk_OCSP_CERTID_num(ids))
1132 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1133 id = sk_OCSP_CERTID_value(ids, i);
1134 name = sk_OPENSSL_STRING_value(names, i);
1135 BIO_printf(out, "%s: ", name);
1137 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1138 &rev, &thisupd, &nextupd)) {
1139 BIO_puts(out, "ERROR: No Status found.\n");
1144 * Check validity: if invalid write to output BIO so we know which
1145 * response this refers to.
1147 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1148 BIO_puts(out, "WARNING: Status times invalid.\n");
1149 ERR_print_errors(out);
1151 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1153 BIO_puts(out, "\tThis Update: ");
1154 ASN1_GENERALIZEDTIME_print(out, thisupd);
1155 BIO_puts(out, "\n");
1158 BIO_puts(out, "\tNext Update: ");
1159 ASN1_GENERALIZEDTIME_print(out, nextupd);
1160 BIO_puts(out, "\n");
1163 if (status != V_OCSP_CERTSTATUS_REVOKED)
1167 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1169 BIO_puts(out, "\tRevocation Time: ");
1170 ASN1_GENERALIZEDTIME_print(out, rev);
1171 BIO_puts(out, "\n");
1175 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1176 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1177 EVP_PKEY *rkey, const EVP_MD *rmd,
1178 STACK_OF(OPENSSL_STRING) *sigopts,
1179 STACK_OF(X509) *rother, unsigned long flags,
1180 int nmin, int ndays, int badsig,
1181 const EVP_MD *resp_md)
1183 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1185 OCSP_BASICRESP *bs = NULL;
1187 EVP_MD_CTX *mctx = NULL;
1188 EVP_PKEY_CTX *pkctx = NULL;
1190 id_count = OCSP_request_onereq_count(req);
1192 if (id_count <= 0) {
1194 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1198 bs = OCSP_BASICRESP_new();
1199 thisupd = X509_gmtime_adj(NULL, 0);
1201 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1203 /* Examine each certificate id in the request */
1204 for (i = 0; i < id_count; i++) {
1206 ASN1_INTEGER *serial;
1210 ASN1_OBJECT *cert_id_md_oid;
1211 const EVP_MD *cert_id_md;
1212 OCSP_CERTID *cid_resp_md = NULL;
1214 one = OCSP_request_onereq_get0(req, i);
1215 cid = OCSP_onereq_get0_id(one);
1217 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1219 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1220 if (cert_id_md == NULL) {
1221 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1225 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1226 X509 *ca_cert = sk_X509_value(ca, jj);
1227 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1229 if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1231 if (resp_md != NULL)
1232 cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1234 OCSP_CERTID_free(ca_id);
1236 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1237 inf = lookup_serial(db, serial);
1239 /* at this point, we can have cid be an alias of cid_resp_md */
1240 cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1243 OCSP_basic_add1_status(bs, cid,
1244 V_OCSP_CERTSTATUS_UNKNOWN,
1245 0, NULL, thisupd, nextupd);
1249 OCSP_basic_add1_status(bs, cid,
1250 V_OCSP_CERTSTATUS_UNKNOWN,
1251 0, NULL, thisupd, nextupd);
1252 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1253 OCSP_basic_add1_status(bs, cid,
1254 V_OCSP_CERTSTATUS_GOOD,
1255 0, NULL, thisupd, nextupd);
1256 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1257 ASN1_OBJECT *inst = NULL;
1258 ASN1_TIME *revtm = NULL;
1259 ASN1_GENERALIZEDTIME *invtm = NULL;
1260 OCSP_SINGLERESP *single;
1263 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1264 single = OCSP_basic_add1_status(bs, cid,
1265 V_OCSP_CERTSTATUS_REVOKED,
1266 reason, revtm, thisupd, nextupd);
1268 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1270 else if (inst != NULL)
1271 OCSP_SINGLERESP_add1_ext_i2d(single,
1272 NID_hold_instruction_code, inst,
1274 ASN1_OBJECT_free(inst);
1275 ASN1_TIME_free(revtm);
1276 ASN1_GENERALIZEDTIME_free(invtm);
1278 OCSP_CERTID_free(cid_resp_md);
1281 OCSP_copy_nonce(bs, req);
1283 mctx = EVP_MD_CTX_new();
1284 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1285 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1288 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1289 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1291 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1292 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1293 ERR_print_errors(bio_err);
1294 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1299 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1300 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1305 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1306 corrupt_signature(sig);
1309 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1312 EVP_MD_CTX_free(mctx);
1313 ASN1_TIME_free(thisupd);
1314 ASN1_TIME_free(nextupd);
1315 OCSP_BASICRESP_free(bs);
1318 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1322 char *itmp, *row[DB_NUMBER], **rrow;
1323 for (i = 0; i < DB_NUMBER; i++)
1325 bn = ASN1_INTEGER_to_BN(ser, NULL);
1326 OPENSSL_assert(bn); /* FIXME: should report an error at this
1327 * point and abort */
1329 itmp = OPENSSL_strdup("00");
1331 itmp = BN_bn2hex(bn);
1332 row[DB_serial] = itmp;
1334 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1339 /* Quick and dirty OCSP server: read in and parse input request */
1341 static BIO *init_responder(const char *port)
1343 #ifdef OPENSSL_NO_SOCK
1345 "Error setting up accept BIO - sockets not supported.\n");
1348 BIO *acbio = NULL, *bufbio = NULL;
1350 bufbio = BIO_new(BIO_f_buffer());
1353 acbio = BIO_new(BIO_s_accept());
1355 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1356 || BIO_set_accept_port(acbio, port) < 0) {
1357 log_message(LOG_ERR, "Error setting up accept BIO");
1361 BIO_set_accept_bios(acbio, bufbio);
1363 if (BIO_do_accept(acbio) <= 0) {
1364 log_message(LOG_ERR, "Error starting accept");
1371 BIO_free_all(acbio);
1377 #ifndef OPENSSL_NO_SOCK
1379 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1381 static int urldecode(char *p)
1383 unsigned char *out = (unsigned char *)p;
1384 unsigned char *save = out;
1389 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1390 /* Don't check, can't fail because of ixdigit() call. */
1391 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1392 | OPENSSL_hexchar2int(p[2]);
1399 return (int)(out - save);
1404 static void socket_timeout(int signum)
1406 if (acfd != (int)INVALID_SOCKET)
1407 (void)shutdown(acfd, SHUT_RD);
1411 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1414 #ifdef OPENSSL_NO_SOCK
1418 OCSP_REQUEST *req = NULL;
1419 char inbuf[2048], reqbuf[2048];
1421 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1426 /* Connection loss before accept() is routine, ignore silently */
1427 if (BIO_do_accept(acbio) <= 0)
1430 cbio = BIO_pop(acbio);
1432 client = BIO_get_peer_name(cbio);
1436 (void) BIO_get_fd(cbio, &acfd);
1441 /* Read the request line. */
1442 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1446 if (strncmp(reqbuf, "GET ", 4) == 0) {
1447 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1448 for (p = reqbuf + 4; *p == ' '; ++p)
1451 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1456 /* Splice off the HTTP version identifier. */
1457 for (q = p; *q; q++)
1460 if (strncmp(q, " HTTP/1.", 8) != 0) {
1461 log_message(LOG_INFO,
1462 "Invalid request -- bad HTTP version: %s", client);
1468 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1469 * 'p' was incremented above to point to the first byte *after* the
1470 * leading slash, so with 'GET / ' it is now an empty string.
1477 log_message(LOG_INFO,
1478 "Invalid request -- bad URL encoding: %s", client);
1481 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1482 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1483 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1486 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1487 getbio = BIO_push(b64, getbio);
1488 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1489 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1493 /* Read and skip past the headers. */
1495 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1498 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1503 /* Clear alarm before we close the client socket */
1508 /* Try to read OCSP request */
1509 if (getbio != NULL) {
1510 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1511 BIO_free_all(getbio);
1513 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1517 log_message(LOG_ERR, "Error parsing OCSP request");
1525 acfd = (int)INVALID_SOCKET;
1531 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1534 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1535 "Content-Length: %d\r\n\r\n";
1538 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1539 i2d_OCSP_RESPONSE_bio(cbio, resp);
1540 (void)BIO_flush(cbio);
1544 #ifndef OPENSSL_NO_SOCK
1545 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1546 const char *host, const char *path,
1547 const char *port, int use_ssl,
1548 STACK_OF(CONF_VALUE) *headers,
1551 SSL_CTX *ctx = NULL;
1552 OCSP_RESPONSE *resp = NULL;
1555 ctx = SSL_CTX_new(TLS_client_method());
1557 BIO_printf(bio_err, "Error creating SSL context.\n");
1560 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1563 resp = (OCSP_RESPONSE *)
1564 app_http_post_asn1(host, port, path, NULL, NULL /* no proxy used */,
1565 ctx, headers, "application/ocsp-request",
1566 (ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST),
1567 req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE));
1570 BIO_printf(bio_err, "Error querying OCSP responder\n");