2 * Copyright 2001-2018 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_NO_OCSP
13 NON_EMPTY_TRANSLATION_UNIT
15 # ifdef OPENSSL_SYS_VMS
16 # define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
26 /* Needs to be included before the openssl headers */
29 # include "internal/sockets.h"
30 # include <openssl/e_os2.h>
31 # include <openssl/crypto.h>
32 # include <openssl/err.h>
33 # include <openssl/ssl.h>
34 # include <openssl/evp.h>
35 # include <openssl/bn.h>
36 # include <openssl/x509v3.h>
37 # include <openssl/rand.h>
40 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
53 # if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
54 && !defined(OPENSSL_NO_POSIX_IO)
56 # include <sys/types.h>
57 # include <sys/wait.h>
60 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
66 # define LOG_WARNING 1
70 # if defined(OPENSSL_SYS_VXWORKS)
72 int setpgid(pid_t pid, pid_t pgid)
84 /* Maximum leeway in validity period: default 5 minutes */
85 # define MAX_VALIDITY_PERIOD (5 * 60)
87 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
88 const EVP_MD *cert_id_md, X509 *issuer,
89 STACK_OF(OCSP_CERTID) *ids);
90 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
91 const EVP_MD *cert_id_md, X509 *issuer,
92 STACK_OF(OCSP_CERTID) *ids);
93 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
94 STACK_OF(OPENSSL_STRING) *names,
95 STACK_OF(OCSP_CERTID) *ids, long nsec,
97 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
98 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
99 EVP_PKEY *rkey, const EVP_MD *md,
100 STACK_OF(OPENSSL_STRING) *sigopts,
101 STACK_OF(X509) *rother, unsigned long flags,
102 int nmin, int ndays, int badsig,
103 const EVP_MD *resp_md);
105 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
106 static BIO *init_responder(const char *port);
107 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
108 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
109 static void log_message(int level, const char *fmt, ...);
111 static int multi = 0;
114 static int acfd = (int) INVALID_SOCKET;
115 static int index_changed(CA_DB *);
116 static void spawn_loop(void);
117 static int print_syslog(const char *str, size_t len, void *levPtr);
118 static void socket_timeout(int signum);
121 # ifndef OPENSSL_NO_SOCK
122 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
124 const STACK_OF(CONF_VALUE) *headers,
125 OCSP_REQUEST *req, int req_timeout);
128 typedef enum OPTION_choice {
129 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
130 OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
131 OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
132 OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
133 OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
134 OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
135 OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
136 OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
137 OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE,
138 OPT_NOCAPATH, OPT_NOCASTORE,
139 OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
140 OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
141 OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
142 OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
150 const OPTIONS ocsp_options[] = {
151 OPT_SECTION("General"),
152 {"help", OPT_HELP, '-', "Display this summary"},
153 {"ignore_err", OPT_IGNORE_ERR, '-',
154 "Ignore error on OCSP request or response and continue running"},
155 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
156 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
157 {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
158 {"no-CAfile", OPT_NOCAFILE, '-',
159 "Do not load the default certificates file"},
160 {"no-CApath", OPT_NOCAPATH, '-',
161 "Do not load certificates from the default certificates directory"},
162 {"no-CAstore", OPT_NOCAPATH, '-',
163 "Do not load certificates from the default certificates store"},
165 OPT_SECTION("Responder"),
166 {"timeout", OPT_TIMEOUT, 'p',
167 "Connection timeout (in seconds) to the OCSP responder"},
168 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
169 "Don't include any certificates in response"},
171 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
173 {"no_certs", OPT_NO_CERTS, '-',
174 "Don't include any certificates in signed request"},
175 {"badsig", OPT_BADSIG, '-',
176 "Corrupt last byte of loaded OSCP response signature (for test)"},
177 {"CA", OPT_CA, '<', "CA certificate"},
178 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
179 {"nrequest", OPT_REQUEST, 'p',
180 "Number of requests to accept (default unlimited)"},
181 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
182 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
183 {"sign_other", OPT_SIGN_OTHER, '<',
184 "Additional certificates to include in signed request"},
185 {"index", OPT_INDEX, '<', "Certificate status index file"},
186 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
187 {"rsigner", OPT_RSIGNER, '<',
188 "Responder certificate to sign responses with"},
189 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
190 {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"},
191 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
192 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
193 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
194 {"header", OPT_HEADER, 's', "key=value header to add"},
195 {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
196 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
198 OPT_SECTION("Client"),
199 {"url", OPT_URL, 's', "Responder URL"},
200 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
201 {"port", OPT_PORT, 'p', "Port to run responder on"},
202 {"out", OPT_OUTFILE, '>', "Output filename"},
203 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
204 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
205 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
206 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
207 "Don't check signature on response"},
208 {"resp_key_id", OPT_RESP_KEY_ID, '-',
209 "Identify response by signing certificate key ID"},
210 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
211 "Don't check signing certificate"},
212 {"text", OPT_TEXT, '-', "Print text form of request and response"},
213 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
214 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
215 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
216 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
217 "Don't do additional checks on signing certificate"},
218 {"no_explicit", OPT_NO_EXPLICIT, '-',
219 "Do not explicitly check the chain, just verify the root"},
220 {"trust_other", OPT_TRUST_OTHER, '-',
221 "Don't verify additional certificates"},
222 {"no_intern", OPT_NO_INTERN, '-',
223 "Don't search certificates contained in response for signer"},
224 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
225 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
226 {"verify_other", OPT_VERIFY_OTHER, '<',
227 "Additional certificates to search for signer"},
228 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
229 {"cert", OPT_CERT, '<', "Certificate to check"},
230 {"serial", OPT_SERIAL, 's', "Serial number to check"},
231 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
232 "Maximum validity discrepancy in seconds"},
233 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
234 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
235 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
236 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
237 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
243 int ocsp_main(int argc, char **argv)
245 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
246 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
247 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
250 EVP_PKEY *key = NULL, *rkey = NULL;
251 OCSP_BASICRESP *bs = NULL;
252 OCSP_REQUEST *req = NULL;
253 OCSP_RESPONSE *resp = NULL;
254 STACK_OF(CONF_VALUE) *headers = NULL;
255 STACK_OF(OCSP_CERTID) *ids = NULL;
256 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
257 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
258 STACK_OF(X509) *issuers = NULL;
259 X509 *issuer = NULL, *cert = NULL;
260 STACK_OF(X509) *rca_cert = NULL;
261 const EVP_MD *resp_certid_md = NULL;
262 X509 *signer = NULL, *rsigner = NULL;
263 X509_STORE *store = NULL;
264 X509_VERIFY_PARAM *vpm = NULL;
265 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
266 char *header, *value;
267 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
268 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
269 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
270 char *rsignfile = NULL, *rkeyfile = NULL;
271 char *passinarg = NULL, *passin = NULL;
272 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
273 char *signfile = NULL, *keyfile = NULL;
274 char *thost = NULL, *tport = NULL, *tpath = NULL;
275 int noCAfile = 0, noCApath = 0, noCAstore = 0;
276 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
277 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
278 int req_text = 0, resp_text = 0, ret = 1;
279 int req_timeout = -1;
280 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
281 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
284 reqnames = sk_OPENSSL_STRING_new_null();
285 if (reqnames == NULL)
287 ids = sk_OCSP_CERTID_new_null();
290 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
293 prog = opt_init(argc, argv, ocsp_options);
294 while ((o = opt_next()) != OPT_EOF) {
299 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
303 opt_help(ocsp_options);
309 #ifndef OPENSSL_NO_SOCK
310 req_timeout = atoi(opt_arg());
317 thost = tport = tpath = NULL;
318 if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
319 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
344 case OPT_RESP_NO_CERTS:
345 rflags |= OCSP_NOCERTS;
347 case OPT_RESP_KEY_ID:
348 rflags |= OCSP_RESPID_KEY;
351 sign_flags |= OCSP_NOCERTS;
353 case OPT_NO_SIGNATURE_VERIFY:
354 verify_flags |= OCSP_NOSIGS;
356 case OPT_NO_CERT_VERIFY:
357 verify_flags |= OCSP_NOVERIFY;
360 verify_flags |= OCSP_NOCHAIN;
362 case OPT_NO_CERT_CHECKS:
363 verify_flags |= OCSP_NOCHECKS;
365 case OPT_NO_EXPLICIT:
366 verify_flags |= OCSP_NOEXPLICIT;
368 case OPT_TRUST_OTHER:
369 verify_flags |= OCSP_TRUSTOTHER;
372 verify_flags |= OCSP_NOINTERN;
378 req_text = resp_text = 1;
393 signfile = opt_arg();
396 verify_certfile = opt_arg();
397 verify_flags |= OCSP_TRUSTOTHER;
400 sign_certfile = opt_arg();
402 case OPT_VERIFY_OTHER:
403 verify_certfile = opt_arg();
424 if (!opt_verify(o, vpm))
428 case OPT_VALIDITY_PERIOD:
429 opt_long(opt_arg(), &nsec);
432 opt_long(opt_arg(), &maxage);
447 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
450 if (issuers == NULL) {
451 if ((issuers = sk_X509_new_null()) == NULL)
454 if (!sk_X509_push(issuers, issuer))
459 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
462 if (cert_id_md == NULL)
463 cert_id_md = EVP_sha1();
464 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
466 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
471 if (cert_id_md == NULL)
472 cert_id_md = EVP_sha1();
473 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
475 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
480 ridx_filename = opt_arg();
483 rca_filename = opt_arg();
486 opt_int(opt_arg(), &nmin);
491 opt_int(opt_arg(), &accept_count);
494 ndays = atoi(opt_arg());
497 rsignfile = opt_arg();
500 rkeyfile = opt_arg();
503 passinarg = opt_arg();
506 rcertfile = opt_arg();
508 case OPT_RMD: /* Response MessageDigest */
509 if (!opt_md(opt_arg(), &rsign_md))
513 if (rsign_sigopts == NULL)
514 rsign_sigopts = sk_OPENSSL_STRING_new_null();
515 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
520 value = strchr(header, '=');
522 BIO_printf(bio_err, "Missing = in header key=value\n");
526 if (!X509V3_add_value(header, value, &headers))
530 resp_certid_md = EVP_get_digestbyname(opt_arg());
531 if (resp_certid_md == NULL)
537 "%s: Digest must be before -cert or -serial\n",
541 if (!opt_md(opt_unknown(), &cert_id_md))
547 multi = atoi(opt_arg());
553 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
557 argc = opt_num_rest();
561 /* Have we anything to do? */
562 if (req == NULL && reqin == NULL
563 && respin == NULL && !(port != NULL && ridx_filename != NULL))
566 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
570 if (req == NULL && (add_nonce != 2))
573 if (req == NULL && reqin != NULL) {
574 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
577 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
580 BIO_printf(bio_err, "Error reading OCSP request\n");
585 if (req == NULL && port != NULL) {
586 acbio = init_responder(port);
591 if (rsignfile != NULL) {
592 if (rkeyfile == NULL)
593 rkeyfile = rsignfile;
594 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
595 if (rsigner == NULL) {
596 BIO_printf(bio_err, "Error loading responder certificate\n");
599 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
600 NULL, "CA certificate"))
602 if (rcertfile != NULL) {
603 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
604 "responder other certificates"))
607 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
608 BIO_printf(bio_err, "Error getting password\n");
611 rkey = load_key(rkeyfile, FORMAT_PEM, 0, passin, NULL,
612 "responder private key");
617 if (ridx_filename != NULL
618 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
620 "Responder mode requires certificate, key, and CA.\n");
624 if (ridx_filename != NULL) {
625 rdb = load_index(ridx_filename, NULL);
626 if (rdb == NULL || index_index(rdb) <= 0) {
633 if (multi && acbio != NULL)
635 if (acbio != NULL && req_timeout > 0)
636 signal(SIGALRM, socket_timeout);
640 log_message(LOG_INFO, "waiting for OCSP client connections...");
646 if (index_changed(rdb)) {
647 CA_DB *newrdb = load_index(ridx_filename, NULL);
649 if (newrdb != NULL && index_index(newrdb) > 0) {
654 log_message(LOG_ERR, "error reloading updated index: %s",
661 if (!do_responder(&req, &cbio, acbio, req_timeout))
666 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
668 send_ocsp_response(cbio, resp);
674 && (signfile != NULL || reqout != NULL
675 || host != NULL || add_nonce || ridx_filename != NULL)) {
676 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
680 if (req != NULL && add_nonce) {
681 if (!OCSP_request_add1_nonce(req, NULL, -1))
685 if (signfile != NULL) {
688 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
689 if (signer == NULL) {
690 BIO_printf(bio_err, "Error loading signer certificate\n");
693 if (sign_certfile != NULL) {
694 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
695 "signer certificates"))
698 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
699 "signer private key");
703 if (!OCSP_request_sign
704 (req, signer, key, NULL, sign_other, sign_flags)) {
705 BIO_printf(bio_err, "Error signing OCSP request\n");
710 if (req_text && req != NULL)
711 OCSP_REQUEST_print(out, req, 0);
713 if (reqout != NULL) {
714 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
717 i2d_OCSP_REQUEST_bio(derbio, req);
722 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
723 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
726 send_ocsp_response(cbio, resp);
727 } else if (host != NULL) {
728 # ifndef OPENSSL_NO_SOCK
729 resp = process_responder(req, host, path,
730 port, use_ssl, headers, req_timeout);
735 "Error creating connect BIO - sockets not supported.\n");
738 } else if (respin != NULL) {
739 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
742 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
745 BIO_printf(bio_err, "Error reading OCSP response\n");
755 if (respout != NULL) {
756 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
759 i2d_OCSP_RESPONSE_bio(derbio, resp);
763 i = OCSP_response_status(resp);
764 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
765 BIO_printf(out, "Responder Error: %s (%d)\n",
766 OCSP_response_status_str(i), i);
772 OCSP_RESPONSE_print(out, resp, 0);
774 /* If running as responder don't verify our own response */
776 /* If not unlimited, see if we took all we should. */
777 if (accept_count != -1 && --accept_count <= 0) {
783 OCSP_REQUEST_free(req);
785 OCSP_RESPONSE_free(resp);
789 if (ridx_filename != NULL) {
795 store = setup_verify(CAfile, noCAfile, CApath, noCApath,
801 X509_STORE_set1_param(store, vpm);
802 if (verify_certfile != NULL) {
803 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
804 "validator certificate"))
808 bs = OCSP_response_get1_basic(resp);
810 BIO_printf(bio_err, "Error parsing response\n");
817 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
819 BIO_printf(bio_err, "WARNING: no nonce in response\n");
821 BIO_printf(bio_err, "Nonce Verify error\n");
827 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
828 if (i <= 0 && issuers) {
829 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
834 BIO_printf(bio_err, "Response Verify Failure\n");
835 ERR_print_errors(bio_err);
838 BIO_printf(bio_err, "Response verify OK\n");
842 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
845 ERR_print_errors(bio_err);
847 X509_STORE_free(store);
848 X509_VERIFY_PARAM_free(vpm);
849 sk_OPENSSL_STRING_free(rsign_sigopts);
853 sk_X509_pop_free(issuers, X509_free);
855 sk_X509_pop_free(rca_cert, X509_free);
860 OCSP_REQUEST_free(req);
861 OCSP_RESPONSE_free(resp);
862 OCSP_BASICRESP_free(bs);
863 sk_OPENSSL_STRING_free(reqnames);
864 sk_OCSP_CERTID_free(ids);
865 sk_X509_pop_free(sign_other, X509_free);
866 sk_X509_pop_free(verify_other, X509_free);
867 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
876 log_message(int level, const char *fmt, ...)
884 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
885 syslog(level, "%s", buf);
887 if (level >= LOG_ERR)
888 ERR_print_errors_cb(print_syslog, &level);
892 BIO_printf(bio_err, "%s: ", prog);
893 BIO_vprintf(bio_err, fmt, ap);
894 BIO_printf(bio_err, "\n");
901 static int print_syslog(const char *str, size_t len, void *levPtr)
903 int level = *(int *)levPtr;
904 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
906 syslog(level, "%.*s", ilen, str);
911 static int index_changed(CA_DB *rdb)
915 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
916 if (rdb->dbst.st_mtime != sb.st_mtime
917 || rdb->dbst.st_ctime != sb.st_ctime
918 || rdb->dbst.st_ino != sb.st_ino
919 || rdb->dbst.st_dev != sb.st_dev) {
920 syslog(LOG_INFO, "index file changed, reloading");
927 static void killall(int ret, pid_t *kidpids)
931 for (i = 0; i < multi; ++i)
933 (void)kill(kidpids[i], SIGTERM);
934 OPENSSL_free(kidpids);
939 static int termsig = 0;
941 static void noteterm (int sig)
947 * Loop spawning up to `multi` child processes, only child processes return
948 * from this function. The parent process loops until receiving a termination
949 * signal, kills extant children and exits without returning.
951 static void spawn_loop(void)
953 pid_t *kidpids = NULL;
958 openlog(prog, LOG_PID, LOG_DAEMON);
961 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
965 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
966 for (i = 0; i < multi; ++i)
969 signal(SIGINT, noteterm);
970 signal(SIGTERM, noteterm);
972 while (termsig == 0) {
976 * Wait for a child to replace when we're at the limit.
977 * Slow down if a child exited abnormally or waitpid() < 0
979 while (termsig == 0 && procs >= multi) {
980 if ((fpid = waitpid(-1, &status, 0)) > 0) {
981 for (i = 0; i < procs; ++i) {
982 if (kidpids[i] == fpid) {
989 syslog(LOG_ERR, "fatal: internal error: "
990 "no matching child slot for pid: %ld",
995 if (WIFEXITED(status))
996 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
997 (long)fpid, WEXITSTATUS(status));
998 else if (WIFSIGNALED(status))
999 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
1000 (long)fpid, WTERMSIG(status),
1002 WCOREDUMP(status) ? " (core dumped)" :
1008 } else if (errno != EINTR) {
1009 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
1010 killall(1, kidpids);
1016 switch(fpid = fork()) {
1017 case -1: /* error */
1018 /* System critically low on memory, pause and try again later */
1022 OPENSSL_free(kidpids);
1023 signal(SIGINT, SIG_DFL);
1024 signal(SIGTERM, SIG_DFL);
1027 if (RAND_poll() <= 0) {
1028 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1032 default: /* parent */
1033 for (i = 0; i < multi; ++i) {
1034 if (kidpids[i] == 0) {
1041 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1042 killall(1, kidpids);
1048 /* The loop above can only break on termsig */
1049 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1050 killall(0, kidpids);
1054 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1055 const EVP_MD *cert_id_md, X509 *issuer,
1056 STACK_OF(OCSP_CERTID) *ids)
1060 if (issuer == NULL) {
1061 BIO_printf(bio_err, "No issuer certificate specified\n");
1065 *req = OCSP_REQUEST_new();
1068 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1069 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1071 if (!OCSP_request_add0_id(*req, id))
1076 BIO_printf(bio_err, "Error Creating OCSP request\n");
1080 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1081 const EVP_MD *cert_id_md, X509 *issuer,
1082 STACK_OF(OCSP_CERTID) *ids)
1086 ASN1_BIT_STRING *ikey;
1089 if (issuer == NULL) {
1090 BIO_printf(bio_err, "No issuer certificate specified\n");
1094 *req = OCSP_REQUEST_new();
1097 iname = X509_get_subject_name(issuer);
1098 ikey = X509_get0_pubkey_bitstr(issuer);
1099 sno = s2i_ASN1_INTEGER(NULL, serial);
1101 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1104 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1105 ASN1_INTEGER_free(sno);
1106 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1108 if (!OCSP_request_add0_id(*req, id))
1113 BIO_printf(bio_err, "Error Creating OCSP request\n");
1117 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1118 STACK_OF(OPENSSL_STRING) *names,
1119 STACK_OF(OCSP_CERTID) *ids, long nsec,
1124 int i, status, reason;
1125 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1127 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1128 || !sk_OCSP_CERTID_num(ids))
1131 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1132 id = sk_OCSP_CERTID_value(ids, i);
1133 name = sk_OPENSSL_STRING_value(names, i);
1134 BIO_printf(out, "%s: ", name);
1136 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1137 &rev, &thisupd, &nextupd)) {
1138 BIO_puts(out, "ERROR: No Status found.\n");
1143 * Check validity: if invalid write to output BIO so we know which
1144 * response this refers to.
1146 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1147 BIO_puts(out, "WARNING: Status times invalid.\n");
1148 ERR_print_errors(out);
1150 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1152 BIO_puts(out, "\tThis Update: ");
1153 ASN1_GENERALIZEDTIME_print(out, thisupd);
1154 BIO_puts(out, "\n");
1157 BIO_puts(out, "\tNext Update: ");
1158 ASN1_GENERALIZEDTIME_print(out, nextupd);
1159 BIO_puts(out, "\n");
1162 if (status != V_OCSP_CERTSTATUS_REVOKED)
1166 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1168 BIO_puts(out, "\tRevocation Time: ");
1169 ASN1_GENERALIZEDTIME_print(out, rev);
1170 BIO_puts(out, "\n");
1174 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1175 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1176 EVP_PKEY *rkey, const EVP_MD *rmd,
1177 STACK_OF(OPENSSL_STRING) *sigopts,
1178 STACK_OF(X509) *rother, unsigned long flags,
1179 int nmin, int ndays, int badsig,
1180 const EVP_MD *resp_md)
1182 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1184 OCSP_BASICRESP *bs = NULL;
1186 EVP_MD_CTX *mctx = NULL;
1187 EVP_PKEY_CTX *pkctx = NULL;
1189 id_count = OCSP_request_onereq_count(req);
1191 if (id_count <= 0) {
1193 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1197 bs = OCSP_BASICRESP_new();
1198 thisupd = X509_gmtime_adj(NULL, 0);
1200 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1202 /* Examine each certificate id in the request */
1203 for (i = 0; i < id_count; i++) {
1205 ASN1_INTEGER *serial;
1209 ASN1_OBJECT *cert_id_md_oid;
1210 const EVP_MD *cert_id_md;
1211 OCSP_CERTID *cid_resp_md = NULL;
1213 one = OCSP_request_onereq_get0(req, i);
1214 cid = OCSP_onereq_get0_id(one);
1216 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1218 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1219 if (cert_id_md == NULL) {
1220 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1224 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1225 X509 *ca_cert = sk_X509_value(ca, jj);
1226 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1228 if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1230 if (resp_md != NULL)
1231 cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1233 OCSP_CERTID_free(ca_id);
1235 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1236 inf = lookup_serial(db, serial);
1238 /* at this point, we can have cid be an alias of cid_resp_md */
1239 cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1242 OCSP_basic_add1_status(bs, cid,
1243 V_OCSP_CERTSTATUS_UNKNOWN,
1244 0, NULL, thisupd, nextupd);
1248 OCSP_basic_add1_status(bs, cid,
1249 V_OCSP_CERTSTATUS_UNKNOWN,
1250 0, NULL, thisupd, nextupd);
1251 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1252 OCSP_basic_add1_status(bs, cid,
1253 V_OCSP_CERTSTATUS_GOOD,
1254 0, NULL, thisupd, nextupd);
1255 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1256 ASN1_OBJECT *inst = NULL;
1257 ASN1_TIME *revtm = NULL;
1258 ASN1_GENERALIZEDTIME *invtm = NULL;
1259 OCSP_SINGLERESP *single;
1262 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1263 single = OCSP_basic_add1_status(bs, cid,
1264 V_OCSP_CERTSTATUS_REVOKED,
1265 reason, revtm, thisupd, nextupd);
1267 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1269 else if (inst != NULL)
1270 OCSP_SINGLERESP_add1_ext_i2d(single,
1271 NID_hold_instruction_code, inst,
1273 ASN1_OBJECT_free(inst);
1274 ASN1_TIME_free(revtm);
1275 ASN1_GENERALIZEDTIME_free(invtm);
1277 OCSP_CERTID_free(cid_resp_md);
1280 OCSP_copy_nonce(bs, req);
1282 mctx = EVP_MD_CTX_new();
1283 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1284 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1287 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1288 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1290 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1291 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1292 ERR_print_errors(bio_err);
1293 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1298 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1299 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1304 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1305 corrupt_signature(sig);
1308 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1311 EVP_MD_CTX_free(mctx);
1312 ASN1_TIME_free(thisupd);
1313 ASN1_TIME_free(nextupd);
1314 OCSP_BASICRESP_free(bs);
1317 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1321 char *itmp, *row[DB_NUMBER], **rrow;
1322 for (i = 0; i < DB_NUMBER; i++)
1324 bn = ASN1_INTEGER_to_BN(ser, NULL);
1325 OPENSSL_assert(bn); /* FIXME: should report an error at this
1326 * point and abort */
1328 itmp = OPENSSL_strdup("00");
1330 itmp = BN_bn2hex(bn);
1331 row[DB_serial] = itmp;
1333 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1338 /* Quick and dirty OCSP server: read in and parse input request */
1340 static BIO *init_responder(const char *port)
1342 # ifdef OPENSSL_NO_SOCK
1344 "Error setting up accept BIO - sockets not supported.\n");
1347 BIO *acbio = NULL, *bufbio = NULL;
1349 bufbio = BIO_new(BIO_f_buffer());
1352 acbio = BIO_new(BIO_s_accept());
1354 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1355 || BIO_set_accept_port(acbio, port) < 0) {
1356 log_message(LOG_ERR, "Error setting up accept BIO");
1360 BIO_set_accept_bios(acbio, bufbio);
1362 if (BIO_do_accept(acbio) <= 0) {
1363 log_message(LOG_ERR, "Error starting accept");
1370 BIO_free_all(acbio);
1376 # ifndef OPENSSL_NO_SOCK
1378 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1380 static int urldecode(char *p)
1382 unsigned char *out = (unsigned char *)p;
1383 unsigned char *save = out;
1388 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1389 /* Don't check, can't fail because of ixdigit() call. */
1390 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1391 | OPENSSL_hexchar2int(p[2]);
1398 return (int)(out - save);
1403 static void socket_timeout(int signum)
1405 if (acfd != (int)INVALID_SOCKET)
1406 (void)shutdown(acfd, SHUT_RD);
1410 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1413 # ifdef OPENSSL_NO_SOCK
1417 OCSP_REQUEST *req = NULL;
1418 char inbuf[2048], reqbuf[2048];
1420 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1425 /* Connection loss before accept() is routine, ignore silently */
1426 if (BIO_do_accept(acbio) <= 0)
1429 cbio = BIO_pop(acbio);
1431 client = BIO_get_peer_name(cbio);
1435 (void) BIO_get_fd(cbio, &acfd);
1440 /* Read the request line. */
1441 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1445 if (strncmp(reqbuf, "GET ", 4) == 0) {
1446 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1447 for (p = reqbuf + 4; *p == ' '; ++p)
1450 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1455 /* Splice off the HTTP version identifier. */
1456 for (q = p; *q; q++)
1459 if (strncmp(q, " HTTP/1.", 8) != 0) {
1460 log_message(LOG_INFO,
1461 "Invalid request -- bad HTTP version: %s", client);
1467 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1468 * 'p' was incremented above to point to the first byte *after* the
1469 * leading slash, so with 'GET / ' it is now an empty string.
1476 log_message(LOG_INFO,
1477 "Invalid request -- bad URL encoding: %s", client);
1480 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1481 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1482 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1485 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1486 getbio = BIO_push(b64, getbio);
1487 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1488 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1492 /* Read and skip past the headers. */
1494 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1497 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1502 /* Clear alarm before we close the client socket */
1507 /* Try to read OCSP request */
1508 if (getbio != NULL) {
1509 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1510 BIO_free_all(getbio);
1512 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1516 log_message(LOG_ERR, "Error parsing OCSP request");
1524 acfd = (int)INVALID_SOCKET;
1530 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1533 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1534 "Content-Length: %d\r\n\r\n";
1537 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1538 i2d_OCSP_RESPONSE_bio(cbio, resp);
1539 (void)BIO_flush(cbio);
1543 # ifndef OPENSSL_NO_SOCK
1544 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1546 const STACK_OF(CONF_VALUE) *headers,
1547 OCSP_REQUEST *req, int req_timeout)
1553 OCSP_REQ_CTX *ctx = NULL;
1554 OCSP_RESPONSE *rsp = NULL;
1558 if (req_timeout != -1)
1559 BIO_set_nbio(cbio, 1);
1561 rv = BIO_do_connect(cbio);
1563 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1564 BIO_puts(bio_err, "Error connecting BIO\n");
1568 if (BIO_get_fd(cbio, &fd) < 0) {
1569 BIO_puts(bio_err, "Can't get connection fd\n");
1573 if (req_timeout != -1 && rv <= 0) {
1575 openssl_fdset(fd, &confds);
1577 tv.tv_sec = req_timeout;
1578 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1580 BIO_puts(bio_err, "Timeout on connect\n");
1585 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1589 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1590 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1591 if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1593 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1597 if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1600 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1604 rv = OCSP_sendreq_nbio(&rsp, ctx);
1607 if (req_timeout == -1)
1610 openssl_fdset(fd, &confds);
1612 tv.tv_sec = req_timeout;
1613 if (BIO_should_read(cbio)) {
1614 rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1615 } else if (BIO_should_write(cbio)) {
1616 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1618 BIO_puts(bio_err, "Unexpected retry condition\n");
1622 BIO_puts(bio_err, "Timeout on request\n");
1626 BIO_puts(bio_err, "Select error\n");
1632 OCSP_REQ_CTX_free(ctx);
1637 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1638 const char *host, const char *path,
1639 const char *port, int use_ssl,
1640 STACK_OF(CONF_VALUE) *headers,
1644 SSL_CTX *ctx = NULL;
1645 OCSP_RESPONSE *resp = NULL;
1647 cbio = BIO_new_connect(host);
1649 BIO_printf(bio_err, "Error creating connect BIO\n");
1653 BIO_set_conn_port(cbio, port);
1656 ctx = SSL_CTX_new(TLS_client_method());
1658 BIO_printf(bio_err, "Error creating SSL context.\n");
1661 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1662 sbio = BIO_new_ssl(ctx, 1);
1663 cbio = BIO_push(sbio, cbio);
1666 resp = query_responder(cbio, host, path, headers, req, req_timeout);
1668 BIO_printf(bio_err, "Error querying OCSP responder\n");