2 * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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 # define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
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>
37 #if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
50 #if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
51 && !defined(OPENSSL_NO_POSIX_IO)
53 # include <sys/types.h>
54 # include <sys/wait.h>
57 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
63 # define LOG_WARNING 1
67 #if defined(OPENSSL_SYS_VXWORKS)
69 int setpgid(pid_t pid, pid_t pgid)
81 /* Maximum leeway in validity period: default 5 minutes */
82 #define MAX_VALIDITY_PERIOD (5 * 60)
84 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
85 const EVP_MD *cert_id_md, X509 *issuer,
86 STACK_OF(OCSP_CERTID) *ids);
87 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
88 const EVP_MD *cert_id_md, X509 *issuer,
89 STACK_OF(OCSP_CERTID) *ids);
90 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
91 STACK_OF(OPENSSL_STRING) *names,
92 STACK_OF(OCSP_CERTID) *ids, long nsec,
94 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
95 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
96 EVP_PKEY *rkey, const EVP_MD *md,
97 STACK_OF(OPENSSL_STRING) *sigopts,
98 STACK_OF(X509) *rother, unsigned long flags,
99 int nmin, int ndays, int badsig);
101 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
102 static BIO *init_responder(const char *port);
103 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
104 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
105 static void log_message(int level, const char *fmt, ...);
107 static int multi = 0;
110 static int acfd = (int) INVALID_SOCKET;
111 static int index_changed(CA_DB *);
112 static void spawn_loop(void);
113 static int print_syslog(const char *str, size_t len, void *levPtr);
114 static void socket_timeout(int signum);
117 #ifndef OPENSSL_NO_SOCK
118 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
120 const STACK_OF(CONF_VALUE) *headers,
121 OCSP_REQUEST *req, int req_timeout);
124 typedef enum OPTION_choice {
125 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
126 OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
127 OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
128 OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
129 OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
130 OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
131 OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
132 OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
133 OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH,
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,
143 const OPTIONS ocsp_options[] = {
144 {"help", OPT_HELP, '-', "Display this summary"},
145 {"out", OPT_OUTFILE, '>', "Output filename"},
146 {"timeout", OPT_TIMEOUT, 'p',
147 "Connection timeout (in seconds) to the OCSP responder"},
148 {"url", OPT_URL, 's', "Responder URL"},
149 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
150 {"port", OPT_PORT, 'p', "Port to run responder on"},
151 {"ignore_err", OPT_IGNORE_ERR, '-',
152 "Ignore error on OCSP request or response and continue running"},
153 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
154 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
155 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
156 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
157 "Don't include any certificates in response"},
158 {"resp_key_id", OPT_RESP_KEY_ID, '-',
159 "Identify response by signing certificate key ID"},
161 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
163 {"no_certs", OPT_NO_CERTS, '-',
164 "Don't include any certificates in signed request"},
165 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
166 "Don't check signature on response"},
167 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
168 "Don't check signing certificate"},
169 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
170 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
171 "Don't do additional checks on signing certificate"},
172 {"no_explicit", OPT_NO_EXPLICIT, '-',
173 "Do not explicitly check the chain, just verify the root"},
174 {"trust_other", OPT_TRUST_OTHER, '-',
175 "Don't verify additional certificates"},
176 {"no_intern", OPT_NO_INTERN, '-',
177 "Don't search certificates contained in response for signer"},
178 {"badsig", OPT_BADSIG, '-',
179 "Corrupt last byte of loaded OSCP response signature (for test)"},
180 {"text", OPT_TEXT, '-', "Print text form of request and response"},
181 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
182 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
183 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
184 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
185 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
186 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
187 {"sign_other", OPT_SIGN_OTHER, '<',
188 "Additional certificates to include in signed request"},
189 {"verify_other", OPT_VERIFY_OTHER, '<',
190 "Additional certificates to search for signer"},
191 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
192 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
193 {"no-CAfile", OPT_NOCAFILE, '-',
194 "Do not load the default certificates file"},
195 {"no-CApath", OPT_NOCAPATH, '-',
196 "Do not load certificates from the default certificates directory"},
197 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
198 "Maximum validity discrepancy in seconds"},
199 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
200 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
201 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
202 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
203 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
204 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
205 {"cert", OPT_CERT, '<', "Certificate to check"},
206 {"serial", OPT_SERIAL, 's', "Serial number to check"},
207 {"index", OPT_INDEX, '<', "Certificate status index file"},
208 {"CA", OPT_CA, '<', "CA certificate"},
209 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
210 {"nrequest", OPT_REQUEST, 'p',
211 "Number of requests to accept (default unlimited)"},
212 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
213 {"rsigner", OPT_RSIGNER, '<',
214 "Responder certificate to sign responses with"},
215 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
216 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
217 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
218 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
219 {"header", OPT_HEADER, 's', "key=value header to add"},
220 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
225 int ocsp_main(int argc, char **argv)
227 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
228 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
229 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
232 EVP_PKEY *key = NULL, *rkey = NULL;
233 OCSP_BASICRESP *bs = NULL;
234 OCSP_REQUEST *req = NULL;
235 OCSP_RESPONSE *resp = NULL;
236 STACK_OF(CONF_VALUE) *headers = NULL;
237 STACK_OF(OCSP_CERTID) *ids = NULL;
238 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
239 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
240 STACK_OF(X509) *issuers = NULL;
241 X509 *issuer = NULL, *cert = NULL;
242 STACK_OF(X509) *rca_cert = NULL;
243 X509 *signer = NULL, *rsigner = NULL;
244 X509_STORE *store = NULL;
245 X509_VERIFY_PARAM *vpm = NULL;
246 const char *CAfile = NULL, *CApath = NULL;
247 char *header, *value;
248 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
249 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
250 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
251 char *rsignfile = NULL, *rkeyfile = NULL;
252 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
253 char *signfile = NULL, *keyfile = NULL;
254 char *thost = NULL, *tport = NULL, *tpath = NULL;
255 int noCAfile = 0, noCApath = 0;
256 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
257 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
258 int req_text = 0, resp_text = 0, ret = 1;
259 int req_timeout = -1;
260 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
261 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
264 reqnames = sk_OPENSSL_STRING_new_null();
265 if (reqnames == NULL)
267 ids = sk_OCSP_CERTID_new_null();
270 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
273 prog = opt_init(argc, argv, ocsp_options);
274 while ((o = opt_next()) != OPT_EOF) {
279 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
283 opt_help(ocsp_options);
289 #ifndef OPENSSL_NO_SOCK
290 req_timeout = atoi(opt_arg());
297 thost = tport = tpath = NULL;
298 if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
299 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
324 case OPT_RESP_NO_CERTS:
325 rflags |= OCSP_NOCERTS;
327 case OPT_RESP_KEY_ID:
328 rflags |= OCSP_RESPID_KEY;
331 sign_flags |= OCSP_NOCERTS;
333 case OPT_NO_SIGNATURE_VERIFY:
334 verify_flags |= OCSP_NOSIGS;
336 case OPT_NO_CERT_VERIFY:
337 verify_flags |= OCSP_NOVERIFY;
340 verify_flags |= OCSP_NOCHAIN;
342 case OPT_NO_CERT_CHECKS:
343 verify_flags |= OCSP_NOCHECKS;
345 case OPT_NO_EXPLICIT:
346 verify_flags |= OCSP_NOEXPLICIT;
348 case OPT_TRUST_OTHER:
349 verify_flags |= OCSP_TRUSTOTHER;
352 verify_flags |= OCSP_NOINTERN;
358 req_text = resp_text = 1;
373 signfile = opt_arg();
376 verify_certfile = opt_arg();
377 verify_flags |= OCSP_TRUSTOTHER;
380 sign_certfile = opt_arg();
382 case OPT_VERIFY_OTHER:
383 verify_certfile = opt_arg();
398 if (!opt_verify(o, vpm))
402 case OPT_VALIDITY_PERIOD:
403 opt_long(opt_arg(), &nsec);
406 opt_long(opt_arg(), &maxage);
421 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
424 if (issuers == NULL) {
425 if ((issuers = sk_X509_new_null()) == NULL)
428 sk_X509_push(issuers, issuer);
432 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
435 if (cert_id_md == NULL)
436 cert_id_md = EVP_sha1();
437 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
439 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
444 if (cert_id_md == NULL)
445 cert_id_md = EVP_sha1();
446 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
448 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
453 ridx_filename = opt_arg();
456 rca_filename = opt_arg();
459 opt_int(opt_arg(), &nmin);
464 opt_int(opt_arg(), &accept_count);
467 ndays = atoi(opt_arg());
470 rsignfile = opt_arg();
473 rkeyfile = opt_arg();
476 rcertfile = opt_arg();
478 case OPT_RMD: /* Response MessageDigest */
479 if (!opt_md(opt_arg(), &rsign_md))
483 if (rsign_sigopts == NULL)
484 rsign_sigopts = sk_OPENSSL_STRING_new_null();
485 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
490 value = strchr(header, '=');
492 BIO_printf(bio_err, "Missing = in header key=value\n");
496 if (!X509V3_add_value(header, value, &headers))
502 "%s: Digest must be before -cert or -serial\n",
506 if (!opt_md(opt_unknown(), &cert_id_md))
512 multi = atoi(opt_arg());
518 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
522 argc = opt_num_rest();
526 /* Have we anything to do? */
527 if (req == NULL && reqin == NULL
528 && respin == NULL && !(port != NULL && ridx_filename != NULL))
531 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
535 if (req == NULL && (add_nonce != 2))
538 if (req == NULL && reqin != NULL) {
539 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
542 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
545 BIO_printf(bio_err, "Error reading OCSP request\n");
550 if (req == NULL && port != NULL) {
551 acbio = init_responder(port);
556 if (rsignfile != NULL) {
557 if (rkeyfile == NULL)
558 rkeyfile = rsignfile;
559 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
560 if (rsigner == NULL) {
561 BIO_printf(bio_err, "Error loading responder certificate\n");
564 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
565 NULL, "CA certificate"))
567 if (rcertfile != NULL) {
568 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
569 "responder other certificates"))
572 rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
573 "responder private key");
578 if (ridx_filename != NULL
579 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
581 "Responder mode requires certificate, key, and CA.\n");
585 if (ridx_filename != NULL) {
586 rdb = load_index(ridx_filename, NULL);
587 if (rdb == NULL || index_index(rdb) <= 0) {
594 if (multi && acbio != NULL)
596 if (acbio != NULL && req_timeout > 0)
597 signal(SIGALRM, socket_timeout);
601 log_message(LOG_INFO, "waiting for OCSP client connections...");
607 if (index_changed(rdb)) {
608 CA_DB *newrdb = load_index(ridx_filename, NULL);
610 if (newrdb != NULL && index_index(newrdb) > 0) {
615 log_message(LOG_ERR, "error reloading updated index: %s",
622 if (!do_responder(&req, &cbio, acbio, req_timeout))
627 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
629 send_ocsp_response(cbio, resp);
635 && (signfile != NULL || reqout != NULL
636 || host != NULL || add_nonce || ridx_filename != NULL)) {
637 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
641 if (req != NULL && add_nonce) {
642 if (!OCSP_request_add1_nonce(req, NULL, -1))
646 if (signfile != NULL) {
649 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
650 if (signer == NULL) {
651 BIO_printf(bio_err, "Error loading signer certificate\n");
654 if (sign_certfile != NULL) {
655 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
656 "signer certificates"))
659 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
660 "signer private key");
664 if (!OCSP_request_sign
665 (req, signer, key, NULL, sign_other, sign_flags)) {
666 BIO_printf(bio_err, "Error signing OCSP request\n");
671 if (req_text && req != NULL)
672 OCSP_REQUEST_print(out, req, 0);
674 if (reqout != NULL) {
675 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
678 i2d_OCSP_REQUEST_bio(derbio, req);
683 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
684 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig);
686 send_ocsp_response(cbio, resp);
687 } else if (host != NULL) {
688 #ifndef OPENSSL_NO_SOCK
689 resp = process_responder(req, host, path,
690 port, use_ssl, headers, req_timeout);
695 "Error creating connect BIO - sockets not supported.\n");
698 } else if (respin != NULL) {
699 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
702 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
705 BIO_printf(bio_err, "Error reading OCSP response\n");
715 if (respout != NULL) {
716 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
719 i2d_OCSP_RESPONSE_bio(derbio, resp);
723 i = OCSP_response_status(resp);
724 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
725 BIO_printf(out, "Responder Error: %s (%d)\n",
726 OCSP_response_status_str(i), i);
732 OCSP_RESPONSE_print(out, resp, 0);
734 /* If running as responder don't verify our own response */
736 /* If not unlimited, see if we took all we should. */
737 if (accept_count != -1 && --accept_count <= 0) {
743 OCSP_REQUEST_free(req);
745 OCSP_RESPONSE_free(resp);
749 if (ridx_filename != NULL) {
755 store = setup_verify(CAfile, CApath, noCAfile, noCApath);
760 X509_STORE_set1_param(store, vpm);
761 if (verify_certfile != NULL) {
762 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
763 "validator certificate"))
767 bs = OCSP_response_get1_basic(resp);
769 BIO_printf(bio_err, "Error parsing response\n");
776 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
778 BIO_printf(bio_err, "WARNING: no nonce in response\n");
780 BIO_printf(bio_err, "Nonce Verify error\n");
786 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
787 if (i <= 0 && issuers) {
788 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
793 BIO_printf(bio_err, "Response Verify Failure\n");
794 ERR_print_errors(bio_err);
797 BIO_printf(bio_err, "Response verify OK\n");
801 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
804 ERR_print_errors(bio_err);
806 X509_STORE_free(store);
807 X509_VERIFY_PARAM_free(vpm);
808 sk_OPENSSL_STRING_free(rsign_sigopts);
812 sk_X509_pop_free(issuers, X509_free);
814 sk_X509_pop_free(rca_cert, X509_free);
819 OCSP_REQUEST_free(req);
820 OCSP_RESPONSE_free(resp);
821 OCSP_BASICRESP_free(bs);
822 sk_OPENSSL_STRING_free(reqnames);
823 sk_OCSP_CERTID_free(ids);
824 sk_X509_pop_free(sign_other, X509_free);
825 sk_X509_pop_free(verify_other, X509_free);
826 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
835 log_message(int level, const char *fmt, ...)
843 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
844 syslog(level, "%s", buf);
846 if (level >= LOG_ERR)
847 ERR_print_errors_cb(print_syslog, &level);
851 BIO_printf(bio_err, "%s: ", prog);
852 BIO_vprintf(bio_err, fmt, ap);
853 BIO_printf(bio_err, "\n");
860 static int print_syslog(const char *str, size_t len, void *levPtr)
862 int level = *(int *)levPtr;
863 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
865 syslog(level, "%.*s", ilen, str);
870 static int index_changed(CA_DB *rdb)
874 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
875 if (rdb->dbst.st_mtime != sb.st_mtime
876 || rdb->dbst.st_ctime != sb.st_ctime
877 || rdb->dbst.st_ino != sb.st_ino
878 || rdb->dbst.st_dev != sb.st_dev) {
879 syslog(LOG_INFO, "index file changed, reloading");
886 static void killall(int ret, pid_t *kidpids)
890 for (i = 0; i < multi; ++i)
892 (void)kill(kidpids[i], SIGTERM);
893 OPENSSL_free(kidpids);
898 static int termsig = 0;
900 static void noteterm (int sig)
906 * Loop spawning up to `multi` child processes, only child processes return
907 * from this function. The parent process loops until receiving a termination
908 * signal, kills extant children and exits without returning.
910 static void spawn_loop(void)
912 pid_t *kidpids = NULL;
917 openlog(prog, LOG_PID, LOG_DAEMON);
920 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
924 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
925 for (i = 0; i < multi; ++i)
928 signal(SIGINT, noteterm);
929 signal(SIGTERM, noteterm);
931 while (termsig == 0) {
935 * Wait for a child to replace when we're at the limit.
936 * Slow down if a child exited abnormally or waitpid() < 0
938 while (termsig == 0 && procs >= multi) {
939 if ((fpid = waitpid(-1, &status, 0)) > 0) {
940 for (i = 0; i < procs; ++i) {
941 if (kidpids[i] == fpid) {
948 syslog(LOG_ERR, "fatal: internal error: "
949 "no matching child slot for pid: %ld",
954 if (WIFEXITED(status))
955 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
956 (long)fpid, WEXITSTATUS(status));
957 else if (WIFSIGNALED(status))
958 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
959 (long)fpid, WTERMSIG(status),
961 WCOREDUMP(status) ? " (core dumped)" :
967 } else if (errno != EINTR) {
968 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
975 switch(fpid = fork()) {
977 /* System critically low on memory, pause and try again later */
981 OPENSSL_free(kidpids);
982 signal(SIGINT, SIG_DFL);
983 signal(SIGTERM, SIG_DFL);
986 if (RAND_poll() <= 0) {
987 syslog(LOG_ERR, "fatal: RAND_poll() failed");
991 default: /* parent */
992 for (i = 0; i < multi; ++i) {
993 if (kidpids[i] == 0) {
1000 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1001 killall(1, kidpids);
1007 /* The loop above can only break on termsig */
1008 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1009 killall(0, kidpids);
1013 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1014 const EVP_MD *cert_id_md, X509 *issuer,
1015 STACK_OF(OCSP_CERTID) *ids)
1019 if (issuer == NULL) {
1020 BIO_printf(bio_err, "No issuer certificate specified\n");
1024 *req = OCSP_REQUEST_new();
1027 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1028 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1030 if (!OCSP_request_add0_id(*req, id))
1035 BIO_printf(bio_err, "Error Creating OCSP request\n");
1039 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1040 const EVP_MD *cert_id_md, X509 *issuer,
1041 STACK_OF(OCSP_CERTID) *ids)
1045 ASN1_BIT_STRING *ikey;
1048 if (issuer == NULL) {
1049 BIO_printf(bio_err, "No issuer certificate specified\n");
1053 *req = OCSP_REQUEST_new();
1056 iname = X509_get_subject_name(issuer);
1057 ikey = X509_get0_pubkey_bitstr(issuer);
1058 sno = s2i_ASN1_INTEGER(NULL, serial);
1060 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1063 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1064 ASN1_INTEGER_free(sno);
1065 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1067 if (!OCSP_request_add0_id(*req, id))
1072 BIO_printf(bio_err, "Error Creating OCSP request\n");
1076 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1077 STACK_OF(OPENSSL_STRING) *names,
1078 STACK_OF(OCSP_CERTID) *ids, long nsec,
1083 int i, status, reason;
1084 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1086 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1087 || !sk_OCSP_CERTID_num(ids))
1090 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1091 id = sk_OCSP_CERTID_value(ids, i);
1092 name = sk_OPENSSL_STRING_value(names, i);
1093 BIO_printf(out, "%s: ", name);
1095 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1096 &rev, &thisupd, &nextupd)) {
1097 BIO_puts(out, "ERROR: No Status found.\n");
1102 * Check validity: if invalid write to output BIO so we know which
1103 * response this refers to.
1105 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1106 BIO_puts(out, "WARNING: Status times invalid.\n");
1107 ERR_print_errors(out);
1109 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1111 BIO_puts(out, "\tThis Update: ");
1112 ASN1_GENERALIZEDTIME_print(out, thisupd);
1113 BIO_puts(out, "\n");
1116 BIO_puts(out, "\tNext Update: ");
1117 ASN1_GENERALIZEDTIME_print(out, nextupd);
1118 BIO_puts(out, "\n");
1121 if (status != V_OCSP_CERTSTATUS_REVOKED)
1125 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1127 BIO_puts(out, "\tRevocation Time: ");
1128 ASN1_GENERALIZEDTIME_print(out, rev);
1129 BIO_puts(out, "\n");
1133 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1134 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1135 EVP_PKEY *rkey, const EVP_MD *rmd,
1136 STACK_OF(OPENSSL_STRING) *sigopts,
1137 STACK_OF(X509) *rother, unsigned long flags,
1138 int nmin, int ndays, int badsig)
1140 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1142 OCSP_BASICRESP *bs = NULL;
1144 EVP_MD_CTX *mctx = NULL;
1145 EVP_PKEY_CTX *pkctx = NULL;
1147 id_count = OCSP_request_onereq_count(req);
1149 if (id_count <= 0) {
1151 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1155 bs = OCSP_BASICRESP_new();
1156 thisupd = X509_gmtime_adj(NULL, 0);
1158 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1160 /* Examine each certificate id in the request */
1161 for (i = 0; i < id_count; i++) {
1163 ASN1_INTEGER *serial;
1167 ASN1_OBJECT *cert_id_md_oid;
1168 const EVP_MD *cert_id_md;
1169 one = OCSP_request_onereq_get0(req, i);
1170 cid = OCSP_onereq_get0_id(one);
1172 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1174 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1175 if (cert_id_md == NULL) {
1176 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1180 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1181 X509 *ca_cert = sk_X509_value(ca, jj);
1182 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1184 if (OCSP_id_issuer_cmp(ca_id, cid) == 0)
1187 OCSP_CERTID_free(ca_id);
1191 OCSP_basic_add1_status(bs, cid,
1192 V_OCSP_CERTSTATUS_UNKNOWN,
1193 0, NULL, thisupd, nextupd);
1196 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1197 inf = lookup_serial(db, serial);
1199 OCSP_basic_add1_status(bs, cid,
1200 V_OCSP_CERTSTATUS_UNKNOWN,
1201 0, NULL, thisupd, nextupd);
1202 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1203 OCSP_basic_add1_status(bs, cid,
1204 V_OCSP_CERTSTATUS_GOOD,
1205 0, NULL, thisupd, nextupd);
1206 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1207 ASN1_OBJECT *inst = NULL;
1208 ASN1_TIME *revtm = NULL;
1209 ASN1_GENERALIZEDTIME *invtm = NULL;
1210 OCSP_SINGLERESP *single;
1212 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1213 single = OCSP_basic_add1_status(bs, cid,
1214 V_OCSP_CERTSTATUS_REVOKED,
1215 reason, revtm, thisupd, nextupd);
1217 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1219 else if (inst != NULL)
1220 OCSP_SINGLERESP_add1_ext_i2d(single,
1221 NID_hold_instruction_code, inst,
1223 ASN1_OBJECT_free(inst);
1224 ASN1_TIME_free(revtm);
1225 ASN1_GENERALIZEDTIME_free(invtm);
1229 OCSP_copy_nonce(bs, req);
1231 mctx = EVP_MD_CTX_new();
1232 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1233 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1236 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1237 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1239 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1240 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1241 ERR_print_errors(bio_err);
1242 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1247 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1248 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1253 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1254 corrupt_signature(sig);
1257 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1260 EVP_MD_CTX_free(mctx);
1261 ASN1_TIME_free(thisupd);
1262 ASN1_TIME_free(nextupd);
1263 OCSP_BASICRESP_free(bs);
1266 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1270 char *itmp, *row[DB_NUMBER], **rrow;
1271 for (i = 0; i < DB_NUMBER; i++)
1273 bn = ASN1_INTEGER_to_BN(ser, NULL);
1274 OPENSSL_assert(bn); /* FIXME: should report an error at this
1275 * point and abort */
1277 itmp = OPENSSL_strdup("00");
1279 itmp = BN_bn2hex(bn);
1280 row[DB_serial] = itmp;
1282 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1287 /* Quick and dirty OCSP server: read in and parse input request */
1289 static BIO *init_responder(const char *port)
1291 #ifdef OPENSSL_NO_SOCK
1293 "Error setting up accept BIO - sockets not supported.\n");
1296 BIO *acbio = NULL, *bufbio = NULL;
1298 bufbio = BIO_new(BIO_f_buffer());
1301 acbio = BIO_new(BIO_s_accept());
1303 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1304 || BIO_set_accept_port(acbio, port) < 0) {
1305 log_message(LOG_ERR, "Error setting up accept BIO");
1309 BIO_set_accept_bios(acbio, bufbio);
1311 if (BIO_do_accept(acbio) <= 0) {
1312 log_message(LOG_ERR, "Error starting accept");
1319 BIO_free_all(acbio);
1325 #ifndef OPENSSL_NO_SOCK
1327 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1329 static int urldecode(char *p)
1331 unsigned char *out = (unsigned char *)p;
1332 unsigned char *save = out;
1337 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1338 /* Don't check, can't fail because of ixdigit() call. */
1339 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1340 | OPENSSL_hexchar2int(p[2]);
1347 return (int)(out - save);
1352 static void socket_timeout(int signum)
1354 if (acfd != (int)INVALID_SOCKET)
1355 (void)shutdown(acfd, SHUT_RD);
1359 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1362 #ifdef OPENSSL_NO_SOCK
1366 OCSP_REQUEST *req = NULL;
1367 char inbuf[2048], reqbuf[2048];
1369 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1374 /* Connection loss before accept() is routine, ignore silently */
1375 if (BIO_do_accept(acbio) <= 0)
1378 cbio = BIO_pop(acbio);
1380 client = BIO_get_peer_name(cbio);
1384 (void) BIO_get_fd(cbio, &acfd);
1389 /* Read the request line. */
1390 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1394 if (strncmp(reqbuf, "GET ", 4) == 0) {
1395 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1396 for (p = reqbuf + 4; *p == ' '; ++p)
1399 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1404 /* Splice off the HTTP version identifier. */
1405 for (q = p; *q; q++)
1408 if (strncmp(q, " HTTP/1.", 8) != 0) {
1409 log_message(LOG_INFO,
1410 "Invalid request -- bad HTTP version: %s", client);
1416 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1417 * 'p' was incremented above to point to the first byte *after* the
1418 * leading slash, so with 'GET / ' it is now an empty string.
1425 log_message(LOG_INFO,
1426 "Invalid request -- bad URL encoding: %s", client);
1429 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1430 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1431 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1434 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1435 getbio = BIO_push(b64, getbio);
1436 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1437 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1441 /* Read and skip past the headers. */
1443 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1446 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1451 /* Clear alarm before we close the client socket */
1456 /* Try to read OCSP request */
1457 if (getbio != NULL) {
1458 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1459 BIO_free_all(getbio);
1461 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1465 log_message(LOG_ERR, "Error parsing OCSP request");
1473 acfd = (int)INVALID_SOCKET;
1479 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1482 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1483 "Content-Length: %d\r\n\r\n";
1486 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1487 i2d_OCSP_RESPONSE_bio(cbio, resp);
1488 (void)BIO_flush(cbio);
1492 #ifndef OPENSSL_NO_SOCK
1493 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1495 const STACK_OF(CONF_VALUE) *headers,
1496 OCSP_REQUEST *req, int req_timeout)
1502 OCSP_REQ_CTX *ctx = NULL;
1503 OCSP_RESPONSE *rsp = NULL;
1507 if (req_timeout != -1)
1508 BIO_set_nbio(cbio, 1);
1510 rv = BIO_do_connect(cbio);
1512 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1513 BIO_puts(bio_err, "Error connecting BIO\n");
1517 if (BIO_get_fd(cbio, &fd) < 0) {
1518 BIO_puts(bio_err, "Can't get connection fd\n");
1522 if (req_timeout != -1 && rv <= 0) {
1524 openssl_fdset(fd, &confds);
1526 tv.tv_sec = req_timeout;
1527 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1529 BIO_puts(bio_err, "Timeout on connect\n");
1534 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1538 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1539 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1540 if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1542 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1546 if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1549 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1553 rv = OCSP_sendreq_nbio(&rsp, ctx);
1556 if (req_timeout == -1)
1559 openssl_fdset(fd, &confds);
1561 tv.tv_sec = req_timeout;
1562 if (BIO_should_read(cbio)) {
1563 rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1564 } else if (BIO_should_write(cbio)) {
1565 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1567 BIO_puts(bio_err, "Unexpected retry condition\n");
1571 BIO_puts(bio_err, "Timeout on request\n");
1575 BIO_puts(bio_err, "Select error\n");
1581 OCSP_REQ_CTX_free(ctx);
1586 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1587 const char *host, const char *path,
1588 const char *port, int use_ssl,
1589 STACK_OF(CONF_VALUE) *headers,
1593 SSL_CTX *ctx = NULL;
1594 OCSP_RESPONSE *resp = NULL;
1596 cbio = BIO_new_connect(host);
1598 BIO_printf(bio_err, "Error creating connect BIO\n");
1602 BIO_set_conn_port(cbio, port);
1605 ctx = SSL_CTX_new(TLS_client_method());
1607 BIO_printf(bio_err, "Error creating SSL context.\n");
1610 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1611 sbio = BIO_new_ssl(ctx, 1);
1612 cbio = BIO_push(sbio, cbio);
1615 resp = query_responder(cbio, host, path, headers, req, req_timeout);
1617 BIO_printf(bio_err, "Error querying OCSP responder\n");