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,
149 const OPTIONS ocsp_options[] = {
150 OPT_SECTION("General"),
151 {"help", OPT_HELP, '-', "Display this summary"},
152 {"ignore_err", OPT_IGNORE_ERR, '-',
153 "Ignore error on OCSP request or response and continue running"},
154 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
155 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
156 {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
157 {"no-CAfile", OPT_NOCAFILE, '-',
158 "Do not load the default certificates file"},
159 {"no-CApath", OPT_NOCAPATH, '-',
160 "Do not load certificates from the default certificates directory"},
161 {"no-CAstore", OPT_NOCAPATH, '-',
162 "Do not load certificates from the default certificates store"},
164 OPT_SECTION("Responder"),
165 {"timeout", OPT_TIMEOUT, 'p',
166 "Connection timeout (in seconds) to the OCSP responder"},
167 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
168 "Don't include any certificates in response"},
170 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
172 {"no_certs", OPT_NO_CERTS, '-',
173 "Don't include any certificates in signed request"},
174 {"badsig", OPT_BADSIG, '-',
175 "Corrupt last byte of loaded OSCP response signature (for test)"},
176 {"CA", OPT_CA, '<', "CA certificate"},
177 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
178 {"nrequest", OPT_REQUEST, 'p',
179 "Number of requests to accept (default unlimited)"},
180 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
181 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
182 {"sign_other", OPT_SIGN_OTHER, '<',
183 "Additional certificates to include in signed request"},
184 {"index", OPT_INDEX, '<', "Certificate status index file"},
185 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
186 {"rsigner", OPT_RSIGNER, '<',
187 "Responder certificate to sign responses with"},
188 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
189 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
190 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
191 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
192 {"header", OPT_HEADER, 's', "key=value header to add"},
193 {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
194 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
196 OPT_SECTION("Client"),
197 {"url", OPT_URL, 's', "Responder URL"},
198 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
199 {"port", OPT_PORT, 'p', "Port to run responder on"},
200 {"out", OPT_OUTFILE, '>', "Output filename"},
201 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
202 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
203 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
204 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
205 "Don't check signature on response"},
206 {"resp_key_id", OPT_RESP_KEY_ID, '-',
207 "Identify response by signing certificate key ID"},
208 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
209 "Don't check signing certificate"},
210 {"text", OPT_TEXT, '-', "Print text form of request and response"},
211 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
212 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
213 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
214 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
215 "Don't do additional checks on signing certificate"},
216 {"no_explicit", OPT_NO_EXPLICIT, '-',
217 "Do not explicitly check the chain, just verify the root"},
218 {"trust_other", OPT_TRUST_OTHER, '-',
219 "Don't verify additional certificates"},
220 {"no_intern", OPT_NO_INTERN, '-',
221 "Don't search certificates contained in response for signer"},
222 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
223 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
224 {"verify_other", OPT_VERIFY_OTHER, '<',
225 "Additional certificates to search for signer"},
226 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
227 {"cert", OPT_CERT, '<', "Certificate to check"},
228 {"serial", OPT_SERIAL, 's', "Serial number to check"},
229 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
230 "Maximum validity discrepancy in seconds"},
231 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
232 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
233 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
234 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
235 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
241 int ocsp_main(int argc, char **argv)
243 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
244 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
245 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
248 EVP_PKEY *key = NULL, *rkey = NULL;
249 OCSP_BASICRESP *bs = NULL;
250 OCSP_REQUEST *req = NULL;
251 OCSP_RESPONSE *resp = NULL;
252 STACK_OF(CONF_VALUE) *headers = NULL;
253 STACK_OF(OCSP_CERTID) *ids = NULL;
254 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
255 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
256 STACK_OF(X509) *issuers = NULL;
257 X509 *issuer = NULL, *cert = NULL;
258 STACK_OF(X509) *rca_cert = NULL;
259 const EVP_MD *resp_certid_md = NULL;
260 X509 *signer = NULL, *rsigner = NULL;
261 X509_STORE *store = NULL;
262 X509_VERIFY_PARAM *vpm = NULL;
263 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
264 char *header, *value;
265 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
266 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
267 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
268 char *rsignfile = NULL, *rkeyfile = NULL;
269 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
270 char *signfile = NULL, *keyfile = NULL;
271 char *thost = NULL, *tport = NULL, *tpath = NULL;
272 int noCAfile = 0, noCApath = 0, noCAstore = 0;
273 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
274 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
275 int req_text = 0, resp_text = 0, ret = 1;
276 int req_timeout = -1;
277 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
278 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
281 reqnames = sk_OPENSSL_STRING_new_null();
282 if (reqnames == NULL)
284 ids = sk_OCSP_CERTID_new_null();
287 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
290 prog = opt_init(argc, argv, ocsp_options);
291 while ((o = opt_next()) != OPT_EOF) {
296 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
300 opt_help(ocsp_options);
306 #ifndef OPENSSL_NO_SOCK
307 req_timeout = atoi(opt_arg());
314 thost = tport = tpath = NULL;
315 if (!OCSP_parse_url(opt_arg(), &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 sk_X509_push(issuers, issuer);
455 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
458 if (cert_id_md == NULL)
459 cert_id_md = EVP_sha1();
460 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
462 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
467 if (cert_id_md == NULL)
468 cert_id_md = EVP_sha1();
469 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
471 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
476 ridx_filename = opt_arg();
479 rca_filename = opt_arg();
482 opt_int(opt_arg(), &nmin);
487 opt_int(opt_arg(), &accept_count);
490 ndays = atoi(opt_arg());
493 rsignfile = opt_arg();
496 rkeyfile = opt_arg();
499 rcertfile = opt_arg();
501 case OPT_RMD: /* Response MessageDigest */
502 if (!opt_md(opt_arg(), &rsign_md))
506 if (rsign_sigopts == NULL)
507 rsign_sigopts = sk_OPENSSL_STRING_new_null();
508 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
513 value = strchr(header, '=');
515 BIO_printf(bio_err, "Missing = in header key=value\n");
519 if (!X509V3_add_value(header, value, &headers))
523 resp_certid_md = EVP_get_digestbyname(opt_arg());
524 if (resp_certid_md == NULL)
530 "%s: Digest must be before -cert or -serial\n",
534 if (!opt_md(opt_unknown(), &cert_id_md))
540 multi = atoi(opt_arg());
546 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
550 argc = opt_num_rest();
554 /* Have we anything to do? */
555 if (req == NULL && reqin == NULL
556 && respin == NULL && !(port != NULL && ridx_filename != NULL))
559 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
563 if (req == NULL && (add_nonce != 2))
566 if (req == NULL && reqin != NULL) {
567 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
570 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
573 BIO_printf(bio_err, "Error reading OCSP request\n");
578 if (req == NULL && port != NULL) {
579 acbio = init_responder(port);
584 if (rsignfile != NULL) {
585 if (rkeyfile == NULL)
586 rkeyfile = rsignfile;
587 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
588 if (rsigner == NULL) {
589 BIO_printf(bio_err, "Error loading responder certificate\n");
592 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
593 NULL, "CA certificate"))
595 if (rcertfile != NULL) {
596 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
597 "responder other certificates"))
600 rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
601 "responder private key");
606 if (ridx_filename != NULL
607 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
609 "Responder mode requires certificate, key, and CA.\n");
613 if (ridx_filename != NULL) {
614 rdb = load_index(ridx_filename, NULL);
615 if (rdb == NULL || index_index(rdb) <= 0) {
622 if (multi && acbio != NULL)
624 if (acbio != NULL && req_timeout > 0)
625 signal(SIGALRM, socket_timeout);
629 log_message(LOG_INFO, "waiting for OCSP client connections...");
635 if (index_changed(rdb)) {
636 CA_DB *newrdb = load_index(ridx_filename, NULL);
638 if (newrdb != NULL && index_index(newrdb) > 0) {
643 log_message(LOG_ERR, "error reloading updated index: %s",
650 if (!do_responder(&req, &cbio, acbio, req_timeout))
655 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
657 send_ocsp_response(cbio, resp);
663 && (signfile != NULL || reqout != NULL
664 || host != NULL || add_nonce || ridx_filename != NULL)) {
665 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
669 if (req != NULL && add_nonce) {
670 if (!OCSP_request_add1_nonce(req, NULL, -1))
674 if (signfile != NULL) {
677 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
678 if (signer == NULL) {
679 BIO_printf(bio_err, "Error loading signer certificate\n");
682 if (sign_certfile != NULL) {
683 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
684 "signer certificates"))
687 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
688 "signer private key");
692 if (!OCSP_request_sign
693 (req, signer, key, NULL, sign_other, sign_flags)) {
694 BIO_printf(bio_err, "Error signing OCSP request\n");
699 if (req_text && req != NULL)
700 OCSP_REQUEST_print(out, req, 0);
702 if (reqout != NULL) {
703 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
706 i2d_OCSP_REQUEST_bio(derbio, req);
711 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
712 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
715 send_ocsp_response(cbio, resp);
716 } else if (host != NULL) {
717 # ifndef OPENSSL_NO_SOCK
718 resp = process_responder(req, host, path,
719 port, use_ssl, headers, req_timeout);
724 "Error creating connect BIO - sockets not supported.\n");
727 } else if (respin != NULL) {
728 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
731 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
734 BIO_printf(bio_err, "Error reading OCSP response\n");
744 if (respout != NULL) {
745 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
748 i2d_OCSP_RESPONSE_bio(derbio, resp);
752 i = OCSP_response_status(resp);
753 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
754 BIO_printf(out, "Responder Error: %s (%d)\n",
755 OCSP_response_status_str(i), i);
761 OCSP_RESPONSE_print(out, resp, 0);
763 /* If running as responder don't verify our own response */
765 /* If not unlimited, see if we took all we should. */
766 if (accept_count != -1 && --accept_count <= 0) {
772 OCSP_REQUEST_free(req);
774 OCSP_RESPONSE_free(resp);
778 if (ridx_filename != NULL) {
784 store = setup_verify(CAfile, noCAfile, CApath, noCApath,
790 X509_STORE_set1_param(store, vpm);
791 if (verify_certfile != NULL) {
792 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
793 "validator certificate"))
797 bs = OCSP_response_get1_basic(resp);
799 BIO_printf(bio_err, "Error parsing response\n");
806 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
808 BIO_printf(bio_err, "WARNING: no nonce in response\n");
810 BIO_printf(bio_err, "Nonce Verify error\n");
816 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
817 if (i <= 0 && issuers) {
818 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
823 BIO_printf(bio_err, "Response Verify Failure\n");
824 ERR_print_errors(bio_err);
827 BIO_printf(bio_err, "Response verify OK\n");
831 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
834 ERR_print_errors(bio_err);
836 X509_STORE_free(store);
837 X509_VERIFY_PARAM_free(vpm);
838 sk_OPENSSL_STRING_free(rsign_sigopts);
842 sk_X509_pop_free(issuers, X509_free);
844 sk_X509_pop_free(rca_cert, X509_free);
849 OCSP_REQUEST_free(req);
850 OCSP_RESPONSE_free(resp);
851 OCSP_BASICRESP_free(bs);
852 sk_OPENSSL_STRING_free(reqnames);
853 sk_OCSP_CERTID_free(ids);
854 sk_X509_pop_free(sign_other, X509_free);
855 sk_X509_pop_free(verify_other, X509_free);
856 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
865 log_message(int level, const char *fmt, ...)
873 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
874 syslog(level, "%s", buf);
876 if (level >= LOG_ERR)
877 ERR_print_errors_cb(print_syslog, &level);
881 BIO_printf(bio_err, "%s: ", prog);
882 BIO_vprintf(bio_err, fmt, ap);
883 BIO_printf(bio_err, "\n");
890 static int print_syslog(const char *str, size_t len, void *levPtr)
892 int level = *(int *)levPtr;
893 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
895 syslog(level, "%.*s", ilen, str);
900 static int index_changed(CA_DB *rdb)
904 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
905 if (rdb->dbst.st_mtime != sb.st_mtime
906 || rdb->dbst.st_ctime != sb.st_ctime
907 || rdb->dbst.st_ino != sb.st_ino
908 || rdb->dbst.st_dev != sb.st_dev) {
909 syslog(LOG_INFO, "index file changed, reloading");
916 static void killall(int ret, pid_t *kidpids)
920 for (i = 0; i < multi; ++i)
922 (void)kill(kidpids[i], SIGTERM);
923 OPENSSL_free(kidpids);
928 static int termsig = 0;
930 static void noteterm (int sig)
936 * Loop spawning up to `multi` child processes, only child processes return
937 * from this function. The parent process loops until receiving a termination
938 * signal, kills extant children and exits without returning.
940 static void spawn_loop(void)
942 pid_t *kidpids = NULL;
947 openlog(prog, LOG_PID, LOG_DAEMON);
950 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
954 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
955 for (i = 0; i < multi; ++i)
958 signal(SIGINT, noteterm);
959 signal(SIGTERM, noteterm);
961 while (termsig == 0) {
965 * Wait for a child to replace when we're at the limit.
966 * Slow down if a child exited abnormally or waitpid() < 0
968 while (termsig == 0 && procs >= multi) {
969 if ((fpid = waitpid(-1, &status, 0)) > 0) {
970 for (i = 0; i < procs; ++i) {
971 if (kidpids[i] == fpid) {
978 syslog(LOG_ERR, "fatal: internal error: "
979 "no matching child slot for pid: %ld",
984 if (WIFEXITED(status))
985 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
986 (long)fpid, WEXITSTATUS(status));
987 else if (WIFSIGNALED(status))
988 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
989 (long)fpid, WTERMSIG(status),
991 WCOREDUMP(status) ? " (core dumped)" :
997 } else if (errno != EINTR) {
998 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
1005 switch(fpid = fork()) {
1006 case -1: /* error */
1007 /* System critically low on memory, pause and try again later */
1011 OPENSSL_free(kidpids);
1012 signal(SIGINT, SIG_DFL);
1013 signal(SIGTERM, SIG_DFL);
1016 if (RAND_poll() <= 0) {
1017 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1021 default: /* parent */
1022 for (i = 0; i < multi; ++i) {
1023 if (kidpids[i] == 0) {
1030 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1031 killall(1, kidpids);
1037 /* The loop above can only break on termsig */
1038 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1039 killall(0, kidpids);
1043 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1044 const EVP_MD *cert_id_md, X509 *issuer,
1045 STACK_OF(OCSP_CERTID) *ids)
1049 if (issuer == NULL) {
1050 BIO_printf(bio_err, "No issuer certificate specified\n");
1054 *req = OCSP_REQUEST_new();
1057 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1058 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1060 if (!OCSP_request_add0_id(*req, id))
1065 BIO_printf(bio_err, "Error Creating OCSP request\n");
1069 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1070 const EVP_MD *cert_id_md, X509 *issuer,
1071 STACK_OF(OCSP_CERTID) *ids)
1075 ASN1_BIT_STRING *ikey;
1078 if (issuer == NULL) {
1079 BIO_printf(bio_err, "No issuer certificate specified\n");
1083 *req = OCSP_REQUEST_new();
1086 iname = X509_get_subject_name(issuer);
1087 ikey = X509_get0_pubkey_bitstr(issuer);
1088 sno = s2i_ASN1_INTEGER(NULL, serial);
1090 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1093 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1094 ASN1_INTEGER_free(sno);
1095 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1097 if (!OCSP_request_add0_id(*req, id))
1102 BIO_printf(bio_err, "Error Creating OCSP request\n");
1106 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1107 STACK_OF(OPENSSL_STRING) *names,
1108 STACK_OF(OCSP_CERTID) *ids, long nsec,
1113 int i, status, reason;
1114 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1116 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1117 || !sk_OCSP_CERTID_num(ids))
1120 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1121 id = sk_OCSP_CERTID_value(ids, i);
1122 name = sk_OPENSSL_STRING_value(names, i);
1123 BIO_printf(out, "%s: ", name);
1125 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1126 &rev, &thisupd, &nextupd)) {
1127 BIO_puts(out, "ERROR: No Status found.\n");
1132 * Check validity: if invalid write to output BIO so we know which
1133 * response this refers to.
1135 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1136 BIO_puts(out, "WARNING: Status times invalid.\n");
1137 ERR_print_errors(out);
1139 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1141 BIO_puts(out, "\tThis Update: ");
1142 ASN1_GENERALIZEDTIME_print(out, thisupd);
1143 BIO_puts(out, "\n");
1146 BIO_puts(out, "\tNext Update: ");
1147 ASN1_GENERALIZEDTIME_print(out, nextupd);
1148 BIO_puts(out, "\n");
1151 if (status != V_OCSP_CERTSTATUS_REVOKED)
1155 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1157 BIO_puts(out, "\tRevocation Time: ");
1158 ASN1_GENERALIZEDTIME_print(out, rev);
1159 BIO_puts(out, "\n");
1163 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1164 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1165 EVP_PKEY *rkey, const EVP_MD *rmd,
1166 STACK_OF(OPENSSL_STRING) *sigopts,
1167 STACK_OF(X509) *rother, unsigned long flags,
1168 int nmin, int ndays, int badsig,
1169 const EVP_MD *resp_md)
1171 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1173 OCSP_BASICRESP *bs = NULL;
1175 EVP_MD_CTX *mctx = NULL;
1176 EVP_PKEY_CTX *pkctx = NULL;
1178 id_count = OCSP_request_onereq_count(req);
1180 if (id_count <= 0) {
1182 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1186 bs = OCSP_BASICRESP_new();
1187 thisupd = X509_gmtime_adj(NULL, 0);
1189 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1191 /* Examine each certificate id in the request */
1192 for (i = 0; i < id_count; i++) {
1194 ASN1_INTEGER *serial;
1198 ASN1_OBJECT *cert_id_md_oid;
1199 const EVP_MD *cert_id_md;
1200 OCSP_CERTID *cid_resp_md = NULL;
1202 one = OCSP_request_onereq_get0(req, i);
1203 cid = OCSP_onereq_get0_id(one);
1205 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1207 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1208 if (cert_id_md == NULL) {
1209 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1213 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1214 X509 *ca_cert = sk_X509_value(ca, jj);
1215 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1217 if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1219 if (resp_md != NULL)
1220 cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1222 OCSP_CERTID_free(ca_id);
1224 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1225 inf = lookup_serial(db, serial);
1227 /* at this point, we can have cid be an alias of cid_resp_md */
1228 cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1231 OCSP_basic_add1_status(bs, cid,
1232 V_OCSP_CERTSTATUS_UNKNOWN,
1233 0, NULL, thisupd, nextupd);
1237 OCSP_basic_add1_status(bs, cid,
1238 V_OCSP_CERTSTATUS_UNKNOWN,
1239 0, NULL, thisupd, nextupd);
1240 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1241 OCSP_basic_add1_status(bs, cid,
1242 V_OCSP_CERTSTATUS_GOOD,
1243 0, NULL, thisupd, nextupd);
1244 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1245 ASN1_OBJECT *inst = NULL;
1246 ASN1_TIME *revtm = NULL;
1247 ASN1_GENERALIZEDTIME *invtm = NULL;
1248 OCSP_SINGLERESP *single;
1251 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1252 single = OCSP_basic_add1_status(bs, cid,
1253 V_OCSP_CERTSTATUS_REVOKED,
1254 reason, revtm, thisupd, nextupd);
1256 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1258 else if (inst != NULL)
1259 OCSP_SINGLERESP_add1_ext_i2d(single,
1260 NID_hold_instruction_code, inst,
1262 ASN1_OBJECT_free(inst);
1263 ASN1_TIME_free(revtm);
1264 ASN1_GENERALIZEDTIME_free(invtm);
1266 OCSP_CERTID_free(cid_resp_md);
1269 OCSP_copy_nonce(bs, req);
1271 mctx = EVP_MD_CTX_new();
1272 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1273 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1276 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1277 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1279 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1280 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1281 ERR_print_errors(bio_err);
1282 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1287 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1288 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1293 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1294 corrupt_signature(sig);
1297 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1300 EVP_MD_CTX_free(mctx);
1301 ASN1_TIME_free(thisupd);
1302 ASN1_TIME_free(nextupd);
1303 OCSP_BASICRESP_free(bs);
1306 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1310 char *itmp, *row[DB_NUMBER], **rrow;
1311 for (i = 0; i < DB_NUMBER; i++)
1313 bn = ASN1_INTEGER_to_BN(ser, NULL);
1314 OPENSSL_assert(bn); /* FIXME: should report an error at this
1315 * point and abort */
1317 itmp = OPENSSL_strdup("00");
1319 itmp = BN_bn2hex(bn);
1320 row[DB_serial] = itmp;
1322 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1327 /* Quick and dirty OCSP server: read in and parse input request */
1329 static BIO *init_responder(const char *port)
1331 # ifdef OPENSSL_NO_SOCK
1333 "Error setting up accept BIO - sockets not supported.\n");
1336 BIO *acbio = NULL, *bufbio = NULL;
1338 bufbio = BIO_new(BIO_f_buffer());
1341 acbio = BIO_new(BIO_s_accept());
1343 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1344 || BIO_set_accept_port(acbio, port) < 0) {
1345 log_message(LOG_ERR, "Error setting up accept BIO");
1349 BIO_set_accept_bios(acbio, bufbio);
1351 if (BIO_do_accept(acbio) <= 0) {
1352 log_message(LOG_ERR, "Error starting accept");
1359 BIO_free_all(acbio);
1365 # ifndef OPENSSL_NO_SOCK
1367 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1369 static int urldecode(char *p)
1371 unsigned char *out = (unsigned char *)p;
1372 unsigned char *save = out;
1377 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1378 /* Don't check, can't fail because of ixdigit() call. */
1379 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1380 | OPENSSL_hexchar2int(p[2]);
1387 return (int)(out - save);
1392 static void socket_timeout(int signum)
1394 if (acfd != (int)INVALID_SOCKET)
1395 (void)shutdown(acfd, SHUT_RD);
1399 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1402 # ifdef OPENSSL_NO_SOCK
1406 OCSP_REQUEST *req = NULL;
1407 char inbuf[2048], reqbuf[2048];
1409 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1414 /* Connection loss before accept() is routine, ignore silently */
1415 if (BIO_do_accept(acbio) <= 0)
1418 cbio = BIO_pop(acbio);
1420 client = BIO_get_peer_name(cbio);
1424 (void) BIO_get_fd(cbio, &acfd);
1429 /* Read the request line. */
1430 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1434 if (strncmp(reqbuf, "GET ", 4) == 0) {
1435 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1436 for (p = reqbuf + 4; *p == ' '; ++p)
1439 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1444 /* Splice off the HTTP version identifier. */
1445 for (q = p; *q; q++)
1448 if (strncmp(q, " HTTP/1.", 8) != 0) {
1449 log_message(LOG_INFO,
1450 "Invalid request -- bad HTTP version: %s", client);
1456 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1457 * 'p' was incremented above to point to the first byte *after* the
1458 * leading slash, so with 'GET / ' it is now an empty string.
1465 log_message(LOG_INFO,
1466 "Invalid request -- bad URL encoding: %s", client);
1469 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1470 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1471 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1474 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1475 getbio = BIO_push(b64, getbio);
1476 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1477 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1481 /* Read and skip past the headers. */
1483 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1486 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1491 /* Clear alarm before we close the client socket */
1496 /* Try to read OCSP request */
1497 if (getbio != NULL) {
1498 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1499 BIO_free_all(getbio);
1501 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1505 log_message(LOG_ERR, "Error parsing OCSP request");
1513 acfd = (int)INVALID_SOCKET;
1519 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1522 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1523 "Content-Length: %d\r\n\r\n";
1526 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1527 i2d_OCSP_RESPONSE_bio(cbio, resp);
1528 (void)BIO_flush(cbio);
1532 # ifndef OPENSSL_NO_SOCK
1533 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1535 const STACK_OF(CONF_VALUE) *headers,
1536 OCSP_REQUEST *req, int req_timeout)
1542 OCSP_REQ_CTX *ctx = NULL;
1543 OCSP_RESPONSE *rsp = NULL;
1547 if (req_timeout != -1)
1548 BIO_set_nbio(cbio, 1);
1550 rv = BIO_do_connect(cbio);
1552 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1553 BIO_puts(bio_err, "Error connecting BIO\n");
1557 if (BIO_get_fd(cbio, &fd) < 0) {
1558 BIO_puts(bio_err, "Can't get connection fd\n");
1562 if (req_timeout != -1 && rv <= 0) {
1564 openssl_fdset(fd, &confds);
1566 tv.tv_sec = req_timeout;
1567 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1569 BIO_puts(bio_err, "Timeout on connect\n");
1574 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1578 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1579 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1580 if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1582 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1586 if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1589 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1593 rv = OCSP_sendreq_nbio(&rsp, ctx);
1596 if (req_timeout == -1)
1599 openssl_fdset(fd, &confds);
1601 tv.tv_sec = req_timeout;
1602 if (BIO_should_read(cbio)) {
1603 rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1604 } else if (BIO_should_write(cbio)) {
1605 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1607 BIO_puts(bio_err, "Unexpected retry condition\n");
1611 BIO_puts(bio_err, "Timeout on request\n");
1615 BIO_puts(bio_err, "Select error\n");
1621 OCSP_REQ_CTX_free(ctx);
1626 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1627 const char *host, const char *path,
1628 const char *port, int use_ssl,
1629 STACK_OF(CONF_VALUE) *headers,
1633 SSL_CTX *ctx = NULL;
1634 OCSP_RESPONSE *resp = NULL;
1636 cbio = BIO_new_connect(host);
1638 BIO_printf(bio_err, "Error creating connect BIO\n");
1642 BIO_set_conn_port(cbio, port);
1645 ctx = SSL_CTX_new(TLS_client_method());
1647 BIO_printf(bio_err, "Error creating SSL context.\n");
1650 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1651 sbio = BIO_new_ssl(ctx, 1);
1652 cbio = BIO_push(sbio, cbio);
1655 resp = query_responder(cbio, host, path, headers, req, req_timeout);
1657 BIO_printf(bio_err, "Error querying OCSP responder\n");