2 * Copyright 2001-2019 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_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);
104 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
105 static BIO *init_responder(const char *port);
106 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
107 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
108 static void log_message(int level, const char *fmt, ...);
110 static int multi = 0;
113 static int acfd = (int) INVALID_SOCKET;
114 static int index_changed(CA_DB *);
115 static void spawn_loop(void);
116 static int print_syslog(const char *str, size_t len, void *levPtr);
117 static void sock_timeout(int signum);
120 # ifndef OPENSSL_NO_SOCK
121 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
123 const STACK_OF(CONF_VALUE) *headers,
124 OCSP_REQUEST *req, int req_timeout);
127 typedef enum OPTION_choice {
128 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
129 OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
130 OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
131 OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
132 OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
133 OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
134 OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
135 OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
136 OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH,
137 OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
138 OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
139 OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
140 OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
146 const OPTIONS ocsp_options[] = {
147 {"help", OPT_HELP, '-', "Display this summary"},
148 {"out", OPT_OUTFILE, '>', "Output filename"},
149 {"timeout", OPT_TIMEOUT, 'p',
150 "Connection timeout (in seconds) to the OCSP responder"},
151 {"url", OPT_URL, 's', "Responder URL"},
152 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
153 {"port", OPT_PORT, 'p', "Port to run responder on"},
154 {"ignore_err", OPT_IGNORE_ERR, '-',
155 "Ignore error on OCSP request or response and continue running"},
156 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
157 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
158 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
159 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
160 "Don't include any certificates in response"},
161 {"resp_key_id", OPT_RESP_KEY_ID, '-',
162 "Identify response by signing certificate key ID"},
164 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
166 {"no_certs", OPT_NO_CERTS, '-',
167 "Don't include any certificates in signed request"},
168 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
169 "Don't check signature on response"},
170 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
171 "Don't check signing certificate"},
172 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
173 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
174 "Don't do additional checks on signing certificate"},
175 {"no_explicit", OPT_NO_EXPLICIT, '-',
176 "Do not explicitly check the chain, just verify the root"},
177 {"trust_other", OPT_TRUST_OTHER, '-',
178 "Don't verify additional certificates"},
179 {"no_intern", OPT_NO_INTERN, '-',
180 "Don't search certificates contained in response for signer"},
181 {"badsig", OPT_BADSIG, '-',
182 "Corrupt last byte of loaded OSCP response signature (for test)"},
183 {"text", OPT_TEXT, '-', "Print text form of request and response"},
184 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
185 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
186 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
187 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
188 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
189 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
190 {"sign_other", OPT_SIGN_OTHER, '<',
191 "Additional certificates to include in signed request"},
192 {"verify_other", OPT_VERIFY_OTHER, '<',
193 "Additional certificates to search for signer"},
194 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
195 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
196 {"no-CAfile", OPT_NOCAFILE, '-',
197 "Do not load the default certificates file"},
198 {"no-CApath", OPT_NOCAPATH, '-',
199 "Do not load certificates from the default certificates directory"},
200 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
201 "Maximum validity discrepancy in seconds"},
202 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
203 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
204 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
205 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
206 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
207 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
208 {"cert", OPT_CERT, '<', "Certificate to check"},
209 {"serial", OPT_SERIAL, 's', "Serial number to check"},
210 {"index", OPT_INDEX, '<', "Certificate status index file"},
211 {"CA", OPT_CA, '<', "CA certificate"},
212 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
213 {"nrequest", OPT_REQUEST, 'p',
214 "Number of requests to accept (default unlimited)"},
215 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
216 {"rsigner", OPT_RSIGNER, '<',
217 "Responder certificate to sign responses with"},
218 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
219 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
220 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
221 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
222 {"header", OPT_HEADER, 's', "key=value header to add"},
223 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
228 int ocsp_main(int argc, char **argv)
230 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
231 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
232 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
235 EVP_PKEY *key = NULL, *rkey = NULL;
236 OCSP_BASICRESP *bs = NULL;
237 OCSP_REQUEST *req = NULL;
238 OCSP_RESPONSE *resp = NULL;
239 STACK_OF(CONF_VALUE) *headers = NULL;
240 STACK_OF(OCSP_CERTID) *ids = NULL;
241 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
242 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
243 STACK_OF(X509) *issuers = NULL;
244 X509 *issuer = NULL, *cert = NULL;
245 STACK_OF(X509) *rca_cert = NULL;
246 X509 *signer = NULL, *rsigner = NULL;
247 X509_STORE *store = NULL;
248 X509_VERIFY_PARAM *vpm = NULL;
249 const char *CAfile = NULL, *CApath = NULL;
250 char *header, *value;
251 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
252 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
253 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
254 char *rsignfile = NULL, *rkeyfile = NULL;
255 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
256 char *signfile = NULL, *keyfile = NULL;
257 char *thost = NULL, *tport = NULL, *tpath = NULL;
258 int noCAfile = 0, noCApath = 0;
259 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
260 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
261 int req_text = 0, resp_text = 0, ret = 1;
262 int req_timeout = -1;
263 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
264 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
267 reqnames = sk_OPENSSL_STRING_new_null();
268 if (reqnames == NULL)
270 ids = sk_OCSP_CERTID_new_null();
273 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
276 prog = opt_init(argc, argv, ocsp_options);
277 while ((o = opt_next()) != OPT_EOF) {
282 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
286 opt_help(ocsp_options);
292 #ifndef OPENSSL_NO_SOCK
293 req_timeout = atoi(opt_arg());
300 thost = tport = tpath = NULL;
301 if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
302 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
327 case OPT_RESP_NO_CERTS:
328 rflags |= OCSP_NOCERTS;
330 case OPT_RESP_KEY_ID:
331 rflags |= OCSP_RESPID_KEY;
334 sign_flags |= OCSP_NOCERTS;
336 case OPT_NO_SIGNATURE_VERIFY:
337 verify_flags |= OCSP_NOSIGS;
339 case OPT_NO_CERT_VERIFY:
340 verify_flags |= OCSP_NOVERIFY;
343 verify_flags |= OCSP_NOCHAIN;
345 case OPT_NO_CERT_CHECKS:
346 verify_flags |= OCSP_NOCHECKS;
348 case OPT_NO_EXPLICIT:
349 verify_flags |= OCSP_NOEXPLICIT;
351 case OPT_TRUST_OTHER:
352 verify_flags |= OCSP_TRUSTOTHER;
355 verify_flags |= OCSP_NOINTERN;
361 req_text = resp_text = 1;
376 signfile = opt_arg();
379 verify_certfile = opt_arg();
380 verify_flags |= OCSP_TRUSTOTHER;
383 sign_certfile = opt_arg();
385 case OPT_VERIFY_OTHER:
386 verify_certfile = opt_arg();
401 if (!opt_verify(o, vpm))
405 case OPT_VALIDITY_PERIOD:
406 opt_long(opt_arg(), &nsec);
409 opt_long(opt_arg(), &maxage);
424 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
427 if (issuers == NULL) {
428 if ((issuers = sk_X509_new_null()) == NULL)
431 sk_X509_push(issuers, issuer);
435 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
438 if (cert_id_md == NULL)
439 cert_id_md = EVP_sha1();
440 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
442 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
447 if (cert_id_md == NULL)
448 cert_id_md = EVP_sha1();
449 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
451 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
456 ridx_filename = opt_arg();
459 rca_filename = opt_arg();
462 opt_int(opt_arg(), &nmin);
467 opt_int(opt_arg(), &accept_count);
470 ndays = atoi(opt_arg());
473 rsignfile = opt_arg();
476 rkeyfile = opt_arg();
479 rcertfile = opt_arg();
481 case OPT_RMD: /* Response MessageDigest */
482 if (!opt_md(opt_arg(), &rsign_md))
486 if (rsign_sigopts == NULL)
487 rsign_sigopts = sk_OPENSSL_STRING_new_null();
488 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
493 value = strchr(header, '=');
495 BIO_printf(bio_err, "Missing = in header key=value\n");
499 if (!X509V3_add_value(header, value, &headers))
505 "%s: Digest must be before -cert or -serial\n",
509 if (!opt_md(opt_unknown(), &cert_id_md))
515 multi = atoi(opt_arg());
521 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
525 argc = opt_num_rest();
529 /* Have we anything to do? */
530 if (req == NULL && reqin == NULL
531 && respin == NULL && !(port != NULL && ridx_filename != NULL))
534 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
538 if (req == NULL && (add_nonce != 2))
541 if (req == NULL && reqin != NULL) {
542 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
545 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
548 BIO_printf(bio_err, "Error reading OCSP request\n");
553 if (req == NULL && port != NULL) {
554 acbio = init_responder(port);
559 if (rsignfile != NULL) {
560 if (rkeyfile == NULL)
561 rkeyfile = rsignfile;
562 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
563 if (rsigner == NULL) {
564 BIO_printf(bio_err, "Error loading responder certificate\n");
567 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
568 NULL, "CA certificate"))
570 if (rcertfile != NULL) {
571 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
572 "responder other certificates"))
575 rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
576 "responder private key");
581 if (ridx_filename != NULL
582 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
584 "Responder mode requires certificate, key, and CA.\n");
588 if (ridx_filename != NULL) {
589 rdb = load_index(ridx_filename, NULL);
590 if (rdb == NULL || index_index(rdb) <= 0) {
597 if (multi && acbio != NULL)
599 if (acbio != NULL && req_timeout > 0)
600 signal(SIGALRM, sock_timeout);
604 log_message(LOG_INFO, "waiting for OCSP client connections...");
610 if (index_changed(rdb)) {
611 CA_DB *newrdb = load_index(ridx_filename, NULL);
613 if (newrdb != NULL && index_index(newrdb) > 0) {
618 log_message(LOG_ERR, "error reloading updated index: %s",
625 if (!do_responder(&req, &cbio, acbio, req_timeout))
630 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
632 send_ocsp_response(cbio, resp);
638 && (signfile != NULL || reqout != NULL
639 || host != NULL || add_nonce || ridx_filename != NULL)) {
640 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
644 if (req != NULL && add_nonce)
645 OCSP_request_add1_nonce(req, NULL, -1);
647 if (signfile != NULL) {
650 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
651 if (signer == NULL) {
652 BIO_printf(bio_err, "Error loading signer certificate\n");
655 if (sign_certfile != NULL) {
656 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
657 "signer certificates"))
660 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
661 "signer private key");
665 if (!OCSP_request_sign
666 (req, signer, key, NULL, sign_other, sign_flags)) {
667 BIO_printf(bio_err, "Error signing OCSP request\n");
672 if (req_text && req != NULL)
673 OCSP_REQUEST_print(out, req, 0);
675 if (reqout != NULL) {
676 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
679 i2d_OCSP_REQUEST_bio(derbio, req);
684 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
685 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig);
687 send_ocsp_response(cbio, resp);
688 } else if (host != NULL) {
689 # ifndef OPENSSL_NO_SOCK
690 resp = process_responder(req, host, path,
691 port, use_ssl, headers, req_timeout);
696 "Error creating connect BIO - sockets not supported.\n");
699 } else if (respin != NULL) {
700 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
703 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
706 BIO_printf(bio_err, "Error reading OCSP response\n");
716 if (respout != NULL) {
717 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
720 i2d_OCSP_RESPONSE_bio(derbio, resp);
724 i = OCSP_response_status(resp);
725 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
726 BIO_printf(out, "Responder Error: %s (%d)\n",
727 OCSP_response_status_str(i), i);
733 OCSP_RESPONSE_print(out, resp, 0);
735 /* If running as responder don't verify our own response */
737 /* If not unlimited, see if we took all we should. */
738 if (accept_count != -1 && --accept_count <= 0) {
744 OCSP_REQUEST_free(req);
746 OCSP_RESPONSE_free(resp);
750 if (ridx_filename != NULL) {
756 store = setup_verify(CAfile, CApath, noCAfile, noCApath);
761 X509_STORE_set1_param(store, vpm);
762 if (verify_certfile != NULL) {
763 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
764 "validator certificate"))
768 bs = OCSP_response_get1_basic(resp);
770 BIO_printf(bio_err, "Error parsing response\n");
777 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
779 BIO_printf(bio_err, "WARNING: no nonce in response\n");
781 BIO_printf(bio_err, "Nonce Verify error\n");
787 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
788 if (i <= 0 && issuers) {
789 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
794 BIO_printf(bio_err, "Response Verify Failure\n");
795 ERR_print_errors(bio_err);
798 BIO_printf(bio_err, "Response verify OK\n");
802 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
805 ERR_print_errors(bio_err);
807 X509_STORE_free(store);
808 X509_VERIFY_PARAM_free(vpm);
809 sk_OPENSSL_STRING_free(rsign_sigopts);
813 sk_X509_pop_free(issuers, X509_free);
815 sk_X509_pop_free(rca_cert, X509_free);
820 OCSP_REQUEST_free(req);
821 OCSP_RESPONSE_free(resp);
822 OCSP_BASICRESP_free(bs);
823 sk_OPENSSL_STRING_free(reqnames);
824 sk_OCSP_CERTID_free(ids);
825 sk_X509_pop_free(sign_other, X509_free);
826 sk_X509_pop_free(verify_other, X509_free);
827 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
836 log_message(int level, const char *fmt, ...)
844 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
845 syslog(level, "%s", buf);
847 if (level >= LOG_ERR)
848 ERR_print_errors_cb(print_syslog, &level);
852 BIO_printf(bio_err, "%s: ", prog);
853 BIO_vprintf(bio_err, fmt, ap);
854 BIO_printf(bio_err, "\n");
861 static int print_syslog(const char *str, size_t len, void *levPtr)
863 int level = *(int *)levPtr;
864 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
866 syslog(level, "%.*s", ilen, str);
871 static int index_changed(CA_DB *rdb)
875 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
876 if (rdb->dbst.st_mtime != sb.st_mtime
877 || rdb->dbst.st_ctime != sb.st_ctime
878 || rdb->dbst.st_ino != sb.st_ino
879 || rdb->dbst.st_dev != sb.st_dev) {
880 syslog(LOG_INFO, "index file changed, reloading");
887 static void killall(int ret, pid_t *kidpids)
891 for (i = 0; i < multi; ++i)
893 (void)kill(kidpids[i], SIGTERM);
894 OPENSSL_free(kidpids);
899 static int termsig = 0;
901 static void noteterm (int sig)
907 * Loop spawning up to `multi` child processes, only child processes return
908 * from this function. The parent process loops until receiving a termination
909 * signal, kills extant children and exits without returning.
911 static void spawn_loop(void)
913 pid_t *kidpids = NULL;
918 openlog(prog, LOG_PID, LOG_DAEMON);
921 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
925 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
926 for (i = 0; i < multi; ++i)
929 signal(SIGINT, noteterm);
930 signal(SIGTERM, noteterm);
932 while (termsig == 0) {
936 * Wait for a child to replace when we're at the limit.
937 * Slow down if a child exited abnormally or waitpid() < 0
939 while (termsig == 0 && procs >= multi) {
940 if ((fpid = waitpid(-1, &status, 0)) > 0) {
941 for (i = 0; i < procs; ++i) {
942 if (kidpids[i] == fpid) {
949 syslog(LOG_ERR, "fatal: internal error: "
950 "no matching child slot for pid: %ld",
955 if (WIFEXITED(status))
956 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
957 (long)fpid, WEXITSTATUS(status));
958 else if (WIFSIGNALED(status))
959 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
960 (long)fpid, WTERMSIG(status),
962 WCOREDUMP(status) ? " (core dumped)" :
968 } else if (errno != EINTR) {
969 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
976 switch(fpid = fork()) {
978 /* System critically low on memory, pause and try again later */
982 OPENSSL_free(kidpids);
983 signal(SIGINT, SIG_DFL);
984 signal(SIGTERM, SIG_DFL);
987 if (RAND_poll() <= 0) {
988 syslog(LOG_ERR, "fatal: RAND_poll() failed");
992 default: /* parent */
993 for (i = 0; i < multi; ++i) {
994 if (kidpids[i] == 0) {
1001 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1002 killall(1, kidpids);
1008 /* The loop above can only break on termsig */
1009 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1010 killall(0, kidpids);
1014 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1015 const EVP_MD *cert_id_md, X509 *issuer,
1016 STACK_OF(OCSP_CERTID) *ids)
1020 if (issuer == NULL) {
1021 BIO_printf(bio_err, "No issuer certificate specified\n");
1025 *req = OCSP_REQUEST_new();
1028 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1029 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1031 if (!OCSP_request_add0_id(*req, id))
1036 BIO_printf(bio_err, "Error Creating OCSP request\n");
1040 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1041 const EVP_MD *cert_id_md, X509 *issuer,
1042 STACK_OF(OCSP_CERTID) *ids)
1046 ASN1_BIT_STRING *ikey;
1049 if (issuer == NULL) {
1050 BIO_printf(bio_err, "No issuer certificate specified\n");
1054 *req = OCSP_REQUEST_new();
1057 iname = X509_get_subject_name(issuer);
1058 ikey = X509_get0_pubkey_bitstr(issuer);
1059 sno = s2i_ASN1_INTEGER(NULL, serial);
1061 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1064 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1065 ASN1_INTEGER_free(sno);
1066 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1068 if (!OCSP_request_add0_id(*req, id))
1073 BIO_printf(bio_err, "Error Creating OCSP request\n");
1077 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1078 STACK_OF(OPENSSL_STRING) *names,
1079 STACK_OF(OCSP_CERTID) *ids, long nsec,
1084 int i, status, reason;
1085 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1087 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1088 || !sk_OCSP_CERTID_num(ids))
1091 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1092 id = sk_OCSP_CERTID_value(ids, i);
1093 name = sk_OPENSSL_STRING_value(names, i);
1094 BIO_printf(out, "%s: ", name);
1096 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1097 &rev, &thisupd, &nextupd)) {
1098 BIO_puts(out, "ERROR: No Status found.\n");
1103 * Check validity: if invalid write to output BIO so we know which
1104 * response this refers to.
1106 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1107 BIO_puts(out, "WARNING: Status times invalid.\n");
1108 ERR_print_errors(out);
1110 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1112 BIO_puts(out, "\tThis Update: ");
1113 ASN1_GENERALIZEDTIME_print(out, thisupd);
1114 BIO_puts(out, "\n");
1117 BIO_puts(out, "\tNext Update: ");
1118 ASN1_GENERALIZEDTIME_print(out, nextupd);
1119 BIO_puts(out, "\n");
1122 if (status != V_OCSP_CERTSTATUS_REVOKED)
1126 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1128 BIO_puts(out, "\tRevocation Time: ");
1129 ASN1_GENERALIZEDTIME_print(out, rev);
1130 BIO_puts(out, "\n");
1134 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1135 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1136 EVP_PKEY *rkey, const EVP_MD *rmd,
1137 STACK_OF(OPENSSL_STRING) *sigopts,
1138 STACK_OF(X509) *rother, unsigned long flags,
1139 int nmin, int ndays, int badsig)
1141 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1143 OCSP_BASICRESP *bs = NULL;
1145 EVP_MD_CTX *mctx = NULL;
1146 EVP_PKEY_CTX *pkctx = NULL;
1148 id_count = OCSP_request_onereq_count(req);
1150 if (id_count <= 0) {
1152 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1156 bs = OCSP_BASICRESP_new();
1157 thisupd = X509_gmtime_adj(NULL, 0);
1159 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1161 /* Examine each certificate id in the request */
1162 for (i = 0; i < id_count; i++) {
1164 ASN1_INTEGER *serial;
1168 ASN1_OBJECT *cert_id_md_oid;
1169 const EVP_MD *cert_id_md;
1170 one = OCSP_request_onereq_get0(req, i);
1171 cid = OCSP_onereq_get0_id(one);
1173 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1175 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1176 if (cert_id_md == NULL) {
1177 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1181 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1182 X509 *ca_cert = sk_X509_value(ca, jj);
1183 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1185 if (OCSP_id_issuer_cmp(ca_id, cid) == 0)
1188 OCSP_CERTID_free(ca_id);
1192 OCSP_basic_add1_status(bs, cid,
1193 V_OCSP_CERTSTATUS_UNKNOWN,
1194 0, NULL, thisupd, nextupd);
1197 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1198 inf = lookup_serial(db, serial);
1200 OCSP_basic_add1_status(bs, cid,
1201 V_OCSP_CERTSTATUS_UNKNOWN,
1202 0, NULL, thisupd, nextupd);
1203 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1204 OCSP_basic_add1_status(bs, cid,
1205 V_OCSP_CERTSTATUS_GOOD,
1206 0, NULL, thisupd, nextupd);
1207 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1208 ASN1_OBJECT *inst = NULL;
1209 ASN1_TIME *revtm = NULL;
1210 ASN1_GENERALIZEDTIME *invtm = NULL;
1211 OCSP_SINGLERESP *single;
1213 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1214 single = OCSP_basic_add1_status(bs, cid,
1215 V_OCSP_CERTSTATUS_REVOKED,
1216 reason, revtm, thisupd, nextupd);
1218 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1220 else if (inst != NULL)
1221 OCSP_SINGLERESP_add1_ext_i2d(single,
1222 NID_hold_instruction_code, inst,
1224 ASN1_OBJECT_free(inst);
1225 ASN1_TIME_free(revtm);
1226 ASN1_GENERALIZEDTIME_free(invtm);
1230 OCSP_copy_nonce(bs, req);
1232 mctx = EVP_MD_CTX_new();
1233 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1234 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1237 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1238 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1240 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1241 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1242 ERR_print_errors(bio_err);
1243 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1248 OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags);
1251 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1252 corrupt_signature(sig);
1255 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1258 EVP_MD_CTX_free(mctx);
1259 ASN1_TIME_free(thisupd);
1260 ASN1_TIME_free(nextupd);
1261 OCSP_BASICRESP_free(bs);
1264 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1268 char *itmp, *row[DB_NUMBER], **rrow;
1269 for (i = 0; i < DB_NUMBER; i++)
1271 bn = ASN1_INTEGER_to_BN(ser, NULL);
1272 OPENSSL_assert(bn); /* FIXME: should report an error at this
1273 * point and abort */
1275 itmp = OPENSSL_strdup("00");
1277 itmp = BN_bn2hex(bn);
1278 row[DB_serial] = itmp;
1280 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1285 /* Quick and dirty OCSP server: read in and parse input request */
1287 static BIO *init_responder(const char *port)
1289 # ifdef OPENSSL_NO_SOCK
1291 "Error setting up accept BIO - sockets not supported.\n");
1294 BIO *acbio = NULL, *bufbio = NULL;
1296 bufbio = BIO_new(BIO_f_buffer());
1299 acbio = BIO_new(BIO_s_accept());
1301 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1302 || BIO_set_accept_port(acbio, port) < 0) {
1303 log_message(LOG_ERR, "Error setting up accept BIO");
1307 BIO_set_accept_bios(acbio, bufbio);
1309 if (BIO_do_accept(acbio) <= 0) {
1310 log_message(LOG_ERR, "Error starting accept");
1317 BIO_free_all(acbio);
1323 # ifndef OPENSSL_NO_SOCK
1325 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1327 static int urldecode(char *p)
1329 unsigned char *out = (unsigned char *)p;
1330 unsigned char *save = out;
1335 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1336 /* Don't check, can't fail because of ixdigit() call. */
1337 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1338 | OPENSSL_hexchar2int(p[2]);
1345 return (int)(out - save);
1350 static void sock_timeout(int signum)
1352 if (acfd != (int)INVALID_SOCKET)
1353 (void)shutdown(acfd, SHUT_RD);
1357 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1360 # ifdef OPENSSL_NO_SOCK
1364 OCSP_REQUEST *req = NULL;
1365 char inbuf[2048], reqbuf[2048];
1367 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1372 /* Connection loss before accept() is routine, ignore silently */
1373 if (BIO_do_accept(acbio) <= 0)
1376 cbio = BIO_pop(acbio);
1378 client = BIO_get_peer_name(cbio);
1382 (void) BIO_get_fd(cbio, &acfd);
1387 /* Read the request line. */
1388 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1392 if (strncmp(reqbuf, "GET ", 4) == 0) {
1393 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1394 for (p = reqbuf + 4; *p == ' '; ++p)
1397 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1402 /* Splice off the HTTP version identifier. */
1403 for (q = p; *q; q++)
1406 if (strncmp(q, " HTTP/1.", 8) != 0) {
1407 log_message(LOG_INFO,
1408 "Invalid request -- bad HTTP version: %s", client);
1414 * Skip "GET / HTTP..." requests often used by load-balancers
1421 log_message(LOG_INFO,
1422 "Invalid request -- bad URL encoding: %s", client);
1425 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1426 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1427 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1430 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1431 getbio = BIO_push(b64, getbio);
1432 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1433 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1437 /* Read and skip past the headers. */
1439 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1442 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1447 /* Clear alarm before we close the client socket */
1452 /* Try to read OCSP request */
1453 if (getbio != NULL) {
1454 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1455 BIO_free_all(getbio);
1457 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1461 log_message(LOG_ERR, "Error parsing OCSP request");
1469 acfd = (int)INVALID_SOCKET;
1475 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1478 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1479 "Content-Length: %d\r\n\r\n";
1482 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1483 i2d_OCSP_RESPONSE_bio(cbio, resp);
1484 (void)BIO_flush(cbio);
1488 # ifndef OPENSSL_NO_SOCK
1489 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1491 const STACK_OF(CONF_VALUE) *headers,
1492 OCSP_REQUEST *req, int req_timeout)
1498 OCSP_REQ_CTX *ctx = NULL;
1499 OCSP_RESPONSE *rsp = NULL;
1503 if (req_timeout != -1)
1504 BIO_set_nbio(cbio, 1);
1506 rv = BIO_do_connect(cbio);
1508 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1509 BIO_puts(bio_err, "Error connecting BIO\n");
1513 if (BIO_get_fd(cbio, &fd) < 0) {
1514 BIO_puts(bio_err, "Can't get connection fd\n");
1518 if (req_timeout != -1 && rv <= 0) {
1520 openssl_fdset(fd, &confds);
1522 tv.tv_sec = req_timeout;
1523 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1525 BIO_puts(bio_err, "Timeout on connect\n");
1530 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1534 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1535 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1536 if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1538 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1542 if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1545 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1549 rv = OCSP_sendreq_nbio(&rsp, ctx);
1552 if (req_timeout == -1)
1555 openssl_fdset(fd, &confds);
1557 tv.tv_sec = req_timeout;
1558 if (BIO_should_read(cbio)) {
1559 rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1560 } else if (BIO_should_write(cbio)) {
1561 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1563 BIO_puts(bio_err, "Unexpected retry condition\n");
1567 BIO_puts(bio_err, "Timeout on request\n");
1571 BIO_puts(bio_err, "Select error\n");
1577 OCSP_REQ_CTX_free(ctx);
1582 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1583 const char *host, const char *path,
1584 const char *port, int use_ssl,
1585 STACK_OF(CONF_VALUE) *headers,
1589 SSL_CTX *ctx = NULL;
1590 OCSP_RESPONSE *resp = NULL;
1592 cbio = BIO_new_connect(host);
1594 BIO_printf(bio_err, "Error creating connect BIO\n");
1598 BIO_set_conn_port(cbio, port);
1601 ctx = SSL_CTX_new(TLS_client_method());
1603 BIO_printf(bio_err, "Error creating SSL context.\n");
1606 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1607 sbio = BIO_new_ssl(ctx, 1);
1608 cbio = BIO_push(sbio, cbio);
1611 resp = query_responder(cbio, host, path, headers, req, req_timeout);
1613 BIO_printf(bio_err, "Error querying OCSP responder\n");