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 sock_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 {"help", OPT_HELP, '-', "Display this summary"},
151 {"out", OPT_OUTFILE, '>', "Output filename"},
152 {"timeout", OPT_TIMEOUT, 'p',
153 "Connection timeout (in seconds) to the OCSP responder"},
154 {"url", OPT_URL, 's', "Responder URL"},
155 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
156 {"port", OPT_PORT, 'p', "Port to run responder on"},
157 {"ignore_err", OPT_IGNORE_ERR, '-',
158 "Ignore error on OCSP request or response and continue running"},
159 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
160 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
161 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
162 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
163 "Don't include any certificates in response"},
164 {"resp_key_id", OPT_RESP_KEY_ID, '-',
165 "Identify response by signing certificate key ID"},
167 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
169 {"no_certs", OPT_NO_CERTS, '-',
170 "Don't include any certificates in signed request"},
171 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
172 "Don't check signature on response"},
173 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
174 "Don't check signing certificate"},
175 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
176 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
177 "Don't do additional checks on signing certificate"},
178 {"no_explicit", OPT_NO_EXPLICIT, '-',
179 "Do not explicitly check the chain, just verify the root"},
180 {"trust_other", OPT_TRUST_OTHER, '-',
181 "Don't verify additional certificates"},
182 {"no_intern", OPT_NO_INTERN, '-',
183 "Don't search certificates contained in response for signer"},
184 {"badsig", OPT_BADSIG, '-',
185 "Corrupt last byte of loaded OSCP response signature (for test)"},
186 {"text", OPT_TEXT, '-', "Print text form of request and response"},
187 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
188 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
189 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
190 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
191 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
192 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
193 {"sign_other", OPT_SIGN_OTHER, '<',
194 "Additional certificates to include in signed request"},
195 {"verify_other", OPT_VERIFY_OTHER, '<',
196 "Additional certificates to search for signer"},
197 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
198 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
199 {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
200 {"no-CAfile", OPT_NOCAFILE, '-',
201 "Do not load the default certificates file"},
202 {"no-CApath", OPT_NOCAPATH, '-',
203 "Do not load certificates from the default certificates directory"},
204 {"no-CAstore", OPT_NOCAPATH, '-',
205 "Do not load certificates from the default certificates store"},
206 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
207 "Maximum validity discrepancy in seconds"},
208 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
209 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
210 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
211 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
212 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
213 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
214 {"cert", OPT_CERT, '<', "Certificate to check"},
215 {"serial", OPT_SERIAL, 's', "Serial number to check"},
216 {"index", OPT_INDEX, '<', "Certificate status index file"},
217 {"CA", OPT_CA, '<', "CA certificate"},
218 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
219 {"nrequest", OPT_REQUEST, 'p',
220 "Number of requests to accept (default unlimited)"},
221 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
222 {"rsigner", OPT_RSIGNER, '<',
223 "Responder certificate to sign responses with"},
224 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
225 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
226 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
227 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
228 {"header", OPT_HEADER, 's', "key=value header to add"},
229 {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
230 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
235 int ocsp_main(int argc, char **argv)
237 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
238 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
239 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
242 EVP_PKEY *key = NULL, *rkey = NULL;
243 OCSP_BASICRESP *bs = NULL;
244 OCSP_REQUEST *req = NULL;
245 OCSP_RESPONSE *resp = NULL;
246 STACK_OF(CONF_VALUE) *headers = NULL;
247 STACK_OF(OCSP_CERTID) *ids = NULL;
248 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
249 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
250 STACK_OF(X509) *issuers = NULL;
251 X509 *issuer = NULL, *cert = NULL;
252 STACK_OF(X509) *rca_cert = NULL;
253 const EVP_MD *resp_certid_md = NULL;
254 X509 *signer = NULL, *rsigner = NULL;
255 X509_STORE *store = NULL;
256 X509_VERIFY_PARAM *vpm = NULL;
257 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
258 char *header, *value;
259 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
260 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
261 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
262 char *rsignfile = NULL, *rkeyfile = NULL;
263 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
264 char *signfile = NULL, *keyfile = NULL;
265 char *thost = NULL, *tport = NULL, *tpath = NULL;
266 int noCAfile = 0, noCApath = 0, noCAstore = 0;
267 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
268 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
269 int req_text = 0, resp_text = 0, ret = 1;
270 int req_timeout = -1;
271 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
272 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
275 reqnames = sk_OPENSSL_STRING_new_null();
276 if (reqnames == NULL)
278 ids = sk_OCSP_CERTID_new_null();
281 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
284 prog = opt_init(argc, argv, ocsp_options);
285 while ((o = opt_next()) != OPT_EOF) {
290 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
294 opt_help(ocsp_options);
300 #ifndef OPENSSL_NO_SOCK
301 req_timeout = atoi(opt_arg());
308 thost = tport = tpath = NULL;
309 if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
310 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
335 case OPT_RESP_NO_CERTS:
336 rflags |= OCSP_NOCERTS;
338 case OPT_RESP_KEY_ID:
339 rflags |= OCSP_RESPID_KEY;
342 sign_flags |= OCSP_NOCERTS;
344 case OPT_NO_SIGNATURE_VERIFY:
345 verify_flags |= OCSP_NOSIGS;
347 case OPT_NO_CERT_VERIFY:
348 verify_flags |= OCSP_NOVERIFY;
351 verify_flags |= OCSP_NOCHAIN;
353 case OPT_NO_CERT_CHECKS:
354 verify_flags |= OCSP_NOCHECKS;
356 case OPT_NO_EXPLICIT:
357 verify_flags |= OCSP_NOEXPLICIT;
359 case OPT_TRUST_OTHER:
360 verify_flags |= OCSP_TRUSTOTHER;
363 verify_flags |= OCSP_NOINTERN;
369 req_text = resp_text = 1;
384 signfile = opt_arg();
387 verify_certfile = opt_arg();
388 verify_flags |= OCSP_TRUSTOTHER;
391 sign_certfile = opt_arg();
393 case OPT_VERIFY_OTHER:
394 verify_certfile = opt_arg();
415 if (!opt_verify(o, vpm))
419 case OPT_VALIDITY_PERIOD:
420 opt_long(opt_arg(), &nsec);
423 opt_long(opt_arg(), &maxage);
438 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
441 if (issuers == NULL) {
442 if ((issuers = sk_X509_new_null()) == NULL)
445 sk_X509_push(issuers, issuer);
449 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
452 if (cert_id_md == NULL)
453 cert_id_md = EVP_sha1();
454 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
456 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
461 if (cert_id_md == NULL)
462 cert_id_md = EVP_sha1();
463 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
465 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
470 ridx_filename = opt_arg();
473 rca_filename = opt_arg();
476 opt_int(opt_arg(), &nmin);
481 opt_int(opt_arg(), &accept_count);
484 ndays = atoi(opt_arg());
487 rsignfile = opt_arg();
490 rkeyfile = opt_arg();
493 rcertfile = opt_arg();
495 case OPT_RMD: /* Response MessageDigest */
496 if (!opt_md(opt_arg(), &rsign_md))
500 if (rsign_sigopts == NULL)
501 rsign_sigopts = sk_OPENSSL_STRING_new_null();
502 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
507 value = strchr(header, '=');
509 BIO_printf(bio_err, "Missing = in header key=value\n");
513 if (!X509V3_add_value(header, value, &headers))
517 resp_certid_md = EVP_get_digestbyname(opt_arg());
518 if (resp_certid_md == NULL)
524 "%s: Digest must be before -cert or -serial\n",
528 if (!opt_md(opt_unknown(), &cert_id_md))
534 multi = atoi(opt_arg());
540 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
544 argc = opt_num_rest();
548 /* Have we anything to do? */
549 if (req == NULL && reqin == NULL
550 && respin == NULL && !(port != NULL && ridx_filename != NULL))
553 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
557 if (req == NULL && (add_nonce != 2))
560 if (req == NULL && reqin != NULL) {
561 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
564 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
567 BIO_printf(bio_err, "Error reading OCSP request\n");
572 if (req == NULL && port != NULL) {
573 acbio = init_responder(port);
578 if (rsignfile != NULL) {
579 if (rkeyfile == NULL)
580 rkeyfile = rsignfile;
581 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
582 if (rsigner == NULL) {
583 BIO_printf(bio_err, "Error loading responder certificate\n");
586 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
587 NULL, "CA certificate"))
589 if (rcertfile != NULL) {
590 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
591 "responder other certificates"))
594 rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
595 "responder private key");
600 if (ridx_filename != NULL
601 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
603 "Responder mode requires certificate, key, and CA.\n");
607 if (ridx_filename != NULL) {
608 rdb = load_index(ridx_filename, NULL);
609 if (rdb == NULL || index_index(rdb) <= 0) {
616 if (multi && acbio != NULL)
618 if (acbio != NULL && req_timeout > 0)
619 signal(SIGALRM, sock_timeout);
623 log_message(LOG_INFO, "waiting for OCSP client connections...");
629 if (index_changed(rdb)) {
630 CA_DB *newrdb = load_index(ridx_filename, NULL);
632 if (newrdb != NULL && index_index(newrdb) > 0) {
637 log_message(LOG_ERR, "error reloading updated index: %s",
644 if (!do_responder(&req, &cbio, acbio, req_timeout))
649 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
651 send_ocsp_response(cbio, resp);
657 && (signfile != NULL || reqout != NULL
658 || host != NULL || add_nonce || ridx_filename != NULL)) {
659 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
663 if (req != NULL && add_nonce) {
664 if (!OCSP_request_add1_nonce(req, NULL, -1))
668 if (signfile != NULL) {
671 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
672 if (signer == NULL) {
673 BIO_printf(bio_err, "Error loading signer certificate\n");
676 if (sign_certfile != NULL) {
677 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
678 "signer certificates"))
681 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
682 "signer private key");
686 if (!OCSP_request_sign
687 (req, signer, key, NULL, sign_other, sign_flags)) {
688 BIO_printf(bio_err, "Error signing OCSP request\n");
693 if (req_text && req != NULL)
694 OCSP_REQUEST_print(out, req, 0);
696 if (reqout != NULL) {
697 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
700 i2d_OCSP_REQUEST_bio(derbio, req);
705 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
706 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
709 send_ocsp_response(cbio, resp);
710 } else if (host != NULL) {
711 # ifndef OPENSSL_NO_SOCK
712 resp = process_responder(req, host, path,
713 port, use_ssl, headers, req_timeout);
718 "Error creating connect BIO - sockets not supported.\n");
721 } else if (respin != NULL) {
722 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
725 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
728 BIO_printf(bio_err, "Error reading OCSP response\n");
738 if (respout != NULL) {
739 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
742 i2d_OCSP_RESPONSE_bio(derbio, resp);
746 i = OCSP_response_status(resp);
747 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
748 BIO_printf(out, "Responder Error: %s (%d)\n",
749 OCSP_response_status_str(i), i);
755 OCSP_RESPONSE_print(out, resp, 0);
757 /* If running as responder don't verify our own response */
759 /* If not unlimited, see if we took all we should. */
760 if (accept_count != -1 && --accept_count <= 0) {
766 OCSP_REQUEST_free(req);
768 OCSP_RESPONSE_free(resp);
772 if (ridx_filename != NULL) {
778 store = setup_verify(CAfile, noCAfile, CApath, noCApath,
784 X509_STORE_set1_param(store, vpm);
785 if (verify_certfile != NULL) {
786 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
787 "validator certificate"))
791 bs = OCSP_response_get1_basic(resp);
793 BIO_printf(bio_err, "Error parsing response\n");
800 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
802 BIO_printf(bio_err, "WARNING: no nonce in response\n");
804 BIO_printf(bio_err, "Nonce Verify error\n");
810 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
811 if (i <= 0 && issuers) {
812 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
817 BIO_printf(bio_err, "Response Verify Failure\n");
818 ERR_print_errors(bio_err);
821 BIO_printf(bio_err, "Response verify OK\n");
825 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
828 ERR_print_errors(bio_err);
830 X509_STORE_free(store);
831 X509_VERIFY_PARAM_free(vpm);
832 sk_OPENSSL_STRING_free(rsign_sigopts);
836 sk_X509_pop_free(issuers, X509_free);
838 sk_X509_pop_free(rca_cert, X509_free);
843 OCSP_REQUEST_free(req);
844 OCSP_RESPONSE_free(resp);
845 OCSP_BASICRESP_free(bs);
846 sk_OPENSSL_STRING_free(reqnames);
847 sk_OCSP_CERTID_free(ids);
848 sk_X509_pop_free(sign_other, X509_free);
849 sk_X509_pop_free(verify_other, X509_free);
850 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
859 log_message(int level, const char *fmt, ...)
867 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
868 syslog(level, "%s", buf);
870 if (level >= LOG_ERR)
871 ERR_print_errors_cb(print_syslog, &level);
875 BIO_printf(bio_err, "%s: ", prog);
876 BIO_vprintf(bio_err, fmt, ap);
877 BIO_printf(bio_err, "\n");
884 static int print_syslog(const char *str, size_t len, void *levPtr)
886 int level = *(int *)levPtr;
887 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
889 syslog(level, "%.*s", ilen, str);
894 static int index_changed(CA_DB *rdb)
898 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
899 if (rdb->dbst.st_mtime != sb.st_mtime
900 || rdb->dbst.st_ctime != sb.st_ctime
901 || rdb->dbst.st_ino != sb.st_ino
902 || rdb->dbst.st_dev != sb.st_dev) {
903 syslog(LOG_INFO, "index file changed, reloading");
910 static void killall(int ret, pid_t *kidpids)
914 for (i = 0; i < multi; ++i)
916 (void)kill(kidpids[i], SIGTERM);
917 OPENSSL_free(kidpids);
922 static int termsig = 0;
924 static void noteterm (int sig)
930 * Loop spawning up to `multi` child processes, only child processes return
931 * from this function. The parent process loops until receiving a termination
932 * signal, kills extant children and exits without returning.
934 static void spawn_loop(void)
936 pid_t *kidpids = NULL;
941 openlog(prog, LOG_PID, LOG_DAEMON);
944 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
948 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
949 for (i = 0; i < multi; ++i)
952 signal(SIGINT, noteterm);
953 signal(SIGTERM, noteterm);
955 while (termsig == 0) {
959 * Wait for a child to replace when we're at the limit.
960 * Slow down if a child exited abnormally or waitpid() < 0
962 while (termsig == 0 && procs >= multi) {
963 if ((fpid = waitpid(-1, &status, 0)) > 0) {
964 for (i = 0; i < procs; ++i) {
965 if (kidpids[i] == fpid) {
972 syslog(LOG_ERR, "fatal: internal error: "
973 "no matching child slot for pid: %ld",
978 if (WIFEXITED(status))
979 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
980 (long)fpid, WEXITSTATUS(status));
981 else if (WIFSIGNALED(status))
982 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
983 (long)fpid, WTERMSIG(status),
985 WCOREDUMP(status) ? " (core dumped)" :
991 } else if (errno != EINTR) {
992 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
999 switch(fpid = fork()) {
1000 case -1: /* error */
1001 /* System critically low on memory, pause and try again later */
1005 OPENSSL_free(kidpids);
1006 signal(SIGINT, SIG_DFL);
1007 signal(SIGTERM, SIG_DFL);
1010 if (RAND_poll() <= 0) {
1011 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1015 default: /* parent */
1016 for (i = 0; i < multi; ++i) {
1017 if (kidpids[i] == 0) {
1024 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1025 killall(1, kidpids);
1031 /* The loop above can only break on termsig */
1032 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1033 killall(0, kidpids);
1037 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1038 const EVP_MD *cert_id_md, X509 *issuer,
1039 STACK_OF(OCSP_CERTID) *ids)
1043 if (issuer == NULL) {
1044 BIO_printf(bio_err, "No issuer certificate specified\n");
1048 *req = OCSP_REQUEST_new();
1051 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1052 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1054 if (!OCSP_request_add0_id(*req, id))
1059 BIO_printf(bio_err, "Error Creating OCSP request\n");
1063 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1064 const EVP_MD *cert_id_md, X509 *issuer,
1065 STACK_OF(OCSP_CERTID) *ids)
1069 ASN1_BIT_STRING *ikey;
1072 if (issuer == NULL) {
1073 BIO_printf(bio_err, "No issuer certificate specified\n");
1077 *req = OCSP_REQUEST_new();
1080 iname = X509_get_subject_name(issuer);
1081 ikey = X509_get0_pubkey_bitstr(issuer);
1082 sno = s2i_ASN1_INTEGER(NULL, serial);
1084 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1087 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1088 ASN1_INTEGER_free(sno);
1089 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1091 if (!OCSP_request_add0_id(*req, id))
1096 BIO_printf(bio_err, "Error Creating OCSP request\n");
1100 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1101 STACK_OF(OPENSSL_STRING) *names,
1102 STACK_OF(OCSP_CERTID) *ids, long nsec,
1107 int i, status, reason;
1108 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1110 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1111 || !sk_OCSP_CERTID_num(ids))
1114 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1115 id = sk_OCSP_CERTID_value(ids, i);
1116 name = sk_OPENSSL_STRING_value(names, i);
1117 BIO_printf(out, "%s: ", name);
1119 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1120 &rev, &thisupd, &nextupd)) {
1121 BIO_puts(out, "ERROR: No Status found.\n");
1126 * Check validity: if invalid write to output BIO so we know which
1127 * response this refers to.
1129 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1130 BIO_puts(out, "WARNING: Status times invalid.\n");
1131 ERR_print_errors(out);
1133 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1135 BIO_puts(out, "\tThis Update: ");
1136 ASN1_GENERALIZEDTIME_print(out, thisupd);
1137 BIO_puts(out, "\n");
1140 BIO_puts(out, "\tNext Update: ");
1141 ASN1_GENERALIZEDTIME_print(out, nextupd);
1142 BIO_puts(out, "\n");
1145 if (status != V_OCSP_CERTSTATUS_REVOKED)
1149 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1151 BIO_puts(out, "\tRevocation Time: ");
1152 ASN1_GENERALIZEDTIME_print(out, rev);
1153 BIO_puts(out, "\n");
1157 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1158 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1159 EVP_PKEY *rkey, const EVP_MD *rmd,
1160 STACK_OF(OPENSSL_STRING) *sigopts,
1161 STACK_OF(X509) *rother, unsigned long flags,
1162 int nmin, int ndays, int badsig,
1163 const EVP_MD *resp_md)
1165 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1167 OCSP_BASICRESP *bs = NULL;
1169 EVP_MD_CTX *mctx = NULL;
1170 EVP_PKEY_CTX *pkctx = NULL;
1172 id_count = OCSP_request_onereq_count(req);
1174 if (id_count <= 0) {
1176 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1180 bs = OCSP_BASICRESP_new();
1181 thisupd = X509_gmtime_adj(NULL, 0);
1183 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1185 /* Examine each certificate id in the request */
1186 for (i = 0; i < id_count; i++) {
1188 ASN1_INTEGER *serial;
1192 ASN1_OBJECT *cert_id_md_oid;
1193 const EVP_MD *cert_id_md;
1194 OCSP_CERTID *cid_resp_md = NULL;
1196 one = OCSP_request_onereq_get0(req, i);
1197 cid = OCSP_onereq_get0_id(one);
1199 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1201 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1202 if (cert_id_md == NULL) {
1203 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1207 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1208 X509 *ca_cert = sk_X509_value(ca, jj);
1209 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1211 if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1213 if (resp_md != NULL)
1214 cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1216 OCSP_CERTID_free(ca_id);
1218 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1219 inf = lookup_serial(db, serial);
1221 /* at this point, we can have cid be an alias of cid_resp_md */
1222 cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1225 OCSP_basic_add1_status(bs, cid,
1226 V_OCSP_CERTSTATUS_UNKNOWN,
1227 0, NULL, thisupd, nextupd);
1231 OCSP_basic_add1_status(bs, cid,
1232 V_OCSP_CERTSTATUS_UNKNOWN,
1233 0, NULL, thisupd, nextupd);
1234 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1235 OCSP_basic_add1_status(bs, cid,
1236 V_OCSP_CERTSTATUS_GOOD,
1237 0, NULL, thisupd, nextupd);
1238 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1239 ASN1_OBJECT *inst = NULL;
1240 ASN1_TIME *revtm = NULL;
1241 ASN1_GENERALIZEDTIME *invtm = NULL;
1242 OCSP_SINGLERESP *single;
1245 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1246 single = OCSP_basic_add1_status(bs, cid,
1247 V_OCSP_CERTSTATUS_REVOKED,
1248 reason, revtm, thisupd, nextupd);
1250 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1252 else if (inst != NULL)
1253 OCSP_SINGLERESP_add1_ext_i2d(single,
1254 NID_hold_instruction_code, inst,
1256 ASN1_OBJECT_free(inst);
1257 ASN1_TIME_free(revtm);
1258 ASN1_GENERALIZEDTIME_free(invtm);
1260 OCSP_CERTID_free(cid_resp_md);
1263 OCSP_copy_nonce(bs, req);
1265 mctx = EVP_MD_CTX_new();
1266 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1267 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1270 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1271 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1273 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1274 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1275 ERR_print_errors(bio_err);
1276 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1281 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1282 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1287 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1288 corrupt_signature(sig);
1291 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1294 EVP_MD_CTX_free(mctx);
1295 ASN1_TIME_free(thisupd);
1296 ASN1_TIME_free(nextupd);
1297 OCSP_BASICRESP_free(bs);
1300 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1304 char *itmp, *row[DB_NUMBER], **rrow;
1305 for (i = 0; i < DB_NUMBER; i++)
1307 bn = ASN1_INTEGER_to_BN(ser, NULL);
1308 OPENSSL_assert(bn); /* FIXME: should report an error at this
1309 * point and abort */
1311 itmp = OPENSSL_strdup("00");
1313 itmp = BN_bn2hex(bn);
1314 row[DB_serial] = itmp;
1316 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1321 /* Quick and dirty OCSP server: read in and parse input request */
1323 static BIO *init_responder(const char *port)
1325 # ifdef OPENSSL_NO_SOCK
1327 "Error setting up accept BIO - sockets not supported.\n");
1330 BIO *acbio = NULL, *bufbio = NULL;
1332 bufbio = BIO_new(BIO_f_buffer());
1335 acbio = BIO_new(BIO_s_accept());
1337 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1338 || BIO_set_accept_port(acbio, port) < 0) {
1339 log_message(LOG_ERR, "Error setting up accept BIO");
1343 BIO_set_accept_bios(acbio, bufbio);
1345 if (BIO_do_accept(acbio) <= 0) {
1346 log_message(LOG_ERR, "Error starting accept");
1353 BIO_free_all(acbio);
1359 # ifndef OPENSSL_NO_SOCK
1361 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1363 static int urldecode(char *p)
1365 unsigned char *out = (unsigned char *)p;
1366 unsigned char *save = out;
1371 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1372 /* Don't check, can't fail because of ixdigit() call. */
1373 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1374 | OPENSSL_hexchar2int(p[2]);
1381 return (int)(out - save);
1386 static void sock_timeout(int signum)
1388 if (acfd != (int)INVALID_SOCKET)
1389 (void)shutdown(acfd, SHUT_RD);
1393 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1396 # ifdef OPENSSL_NO_SOCK
1400 OCSP_REQUEST *req = NULL;
1401 char inbuf[2048], reqbuf[2048];
1403 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1408 /* Connection loss before accept() is routine, ignore silently */
1409 if (BIO_do_accept(acbio) <= 0)
1412 cbio = BIO_pop(acbio);
1414 client = BIO_get_peer_name(cbio);
1418 (void) BIO_get_fd(cbio, &acfd);
1423 /* Read the request line. */
1424 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1428 if (strncmp(reqbuf, "GET ", 4) == 0) {
1429 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1430 for (p = reqbuf + 4; *p == ' '; ++p)
1433 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1438 /* Splice off the HTTP version identifier. */
1439 for (q = p; *q; q++)
1442 if (strncmp(q, " HTTP/1.", 8) != 0) {
1443 log_message(LOG_INFO,
1444 "Invalid request -- bad HTTP version: %s", client);
1450 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1451 * 'p' was incremented above to point to the first byte *after* the
1452 * leading slash, so with 'GET / ' it is now an empty string.
1459 log_message(LOG_INFO,
1460 "Invalid request -- bad URL encoding: %s", client);
1463 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1464 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1465 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1468 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1469 getbio = BIO_push(b64, getbio);
1470 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1471 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1475 /* Read and skip past the headers. */
1477 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1480 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1485 /* Clear alarm before we close the client socket */
1490 /* Try to read OCSP request */
1491 if (getbio != NULL) {
1492 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1493 BIO_free_all(getbio);
1495 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1499 log_message(LOG_ERR, "Error parsing OCSP request");
1507 acfd = (int)INVALID_SOCKET;
1513 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1516 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1517 "Content-Length: %d\r\n\r\n";
1520 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1521 i2d_OCSP_RESPONSE_bio(cbio, resp);
1522 (void)BIO_flush(cbio);
1526 # ifndef OPENSSL_NO_SOCK
1527 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1529 const STACK_OF(CONF_VALUE) *headers,
1530 OCSP_REQUEST *req, int req_timeout)
1536 OCSP_REQ_CTX *ctx = NULL;
1537 OCSP_RESPONSE *rsp = NULL;
1541 if (req_timeout != -1)
1542 BIO_set_nbio(cbio, 1);
1544 rv = BIO_do_connect(cbio);
1546 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1547 BIO_puts(bio_err, "Error connecting BIO\n");
1551 if (BIO_get_fd(cbio, &fd) < 0) {
1552 BIO_puts(bio_err, "Can't get connection fd\n");
1556 if (req_timeout != -1 && rv <= 0) {
1558 openssl_fdset(fd, &confds);
1560 tv.tv_sec = req_timeout;
1561 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1563 BIO_puts(bio_err, "Timeout on connect\n");
1568 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1572 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1573 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1574 if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1576 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1580 if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1583 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1587 rv = OCSP_sendreq_nbio(&rsp, ctx);
1590 if (req_timeout == -1)
1593 openssl_fdset(fd, &confds);
1595 tv.tv_sec = req_timeout;
1596 if (BIO_should_read(cbio)) {
1597 rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1598 } else if (BIO_should_write(cbio)) {
1599 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1601 BIO_puts(bio_err, "Unexpected retry condition\n");
1605 BIO_puts(bio_err, "Timeout on request\n");
1609 BIO_puts(bio_err, "Select error\n");
1615 OCSP_REQ_CTX_free(ctx);
1620 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1621 const char *host, const char *path,
1622 const char *port, int use_ssl,
1623 STACK_OF(CONF_VALUE) *headers,
1627 SSL_CTX *ctx = NULL;
1628 OCSP_RESPONSE *resp = NULL;
1630 cbio = BIO_new_connect(host);
1632 BIO_printf(bio_err, "Error creating connect BIO\n");
1636 BIO_set_conn_port(cbio, port);
1639 ctx = SSL_CTX_new(TLS_client_method());
1641 BIO_printf(bio_err, "Error creating SSL context.\n");
1644 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1645 sbio = BIO_new_ssl(ctx, 1);
1646 cbio = BIO_push(sbio, cbio);
1649 resp = query_responder(cbio, host, path, headers, req, req_timeout);
1651 BIO_printf(bio_err, "Error querying OCSP responder\n");