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_NOCAFILE, OPT_NOCAPATH,
138 OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
139 OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
140 OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
141 OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
148 const OPTIONS ocsp_options[] = {
149 {"help", OPT_HELP, '-', "Display this summary"},
150 {"out", OPT_OUTFILE, '>', "Output filename"},
151 {"timeout", OPT_TIMEOUT, 'p',
152 "Connection timeout (in seconds) to the OCSP responder"},
153 {"url", OPT_URL, 's', "Responder URL"},
154 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
155 {"port", OPT_PORT, 'p', "Port to run responder on"},
156 {"ignore_err", OPT_IGNORE_ERR, '-',
157 "Ignore error on OCSP request or response and continue running"},
158 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
159 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
160 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
161 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
162 "Don't include any certificates in response"},
163 {"resp_key_id", OPT_RESP_KEY_ID, '-',
164 "Identify response by signing certificate key ID"},
166 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
168 {"no_certs", OPT_NO_CERTS, '-',
169 "Don't include any certificates in signed request"},
170 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
171 "Don't check signature on response"},
172 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
173 "Don't check signing certificate"},
174 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
175 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
176 "Don't do additional checks on signing certificate"},
177 {"no_explicit", OPT_NO_EXPLICIT, '-',
178 "Do not explicitly check the chain, just verify the root"},
179 {"trust_other", OPT_TRUST_OTHER, '-',
180 "Don't verify additional certificates"},
181 {"no_intern", OPT_NO_INTERN, '-',
182 "Don't search certificates contained in response for signer"},
183 {"badsig", OPT_BADSIG, '-',
184 "Corrupt last byte of loaded OSCP response signature (for test)"},
185 {"text", OPT_TEXT, '-', "Print text form of request and response"},
186 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
187 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
188 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
189 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
190 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
191 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
192 {"sign_other", OPT_SIGN_OTHER, '<',
193 "Additional certificates to include in signed request"},
194 {"verify_other", OPT_VERIFY_OTHER, '<',
195 "Additional certificates to search for signer"},
196 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
197 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
198 {"no-CAfile", OPT_NOCAFILE, '-',
199 "Do not load the default certificates file"},
200 {"no-CApath", OPT_NOCAPATH, '-',
201 "Do not load certificates from the default certificates directory"},
202 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
203 "Maximum validity discrepancy in seconds"},
204 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
205 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
206 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
207 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
208 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
209 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
210 {"cert", OPT_CERT, '<', "Certificate to check"},
211 {"serial", OPT_SERIAL, 's', "Serial number to check"},
212 {"index", OPT_INDEX, '<', "Certificate status index file"},
213 {"CA", OPT_CA, '<', "CA certificate"},
214 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
215 {"nrequest", OPT_REQUEST, 'p',
216 "Number of requests to accept (default unlimited)"},
217 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
218 {"rsigner", OPT_RSIGNER, '<',
219 "Responder certificate to sign responses with"},
220 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
221 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
222 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
223 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
224 {"header", OPT_HEADER, 's', "key=value header to add"},
225 {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
226 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
231 int ocsp_main(int argc, char **argv)
233 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
234 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
235 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
238 EVP_PKEY *key = NULL, *rkey = NULL;
239 OCSP_BASICRESP *bs = NULL;
240 OCSP_REQUEST *req = NULL;
241 OCSP_RESPONSE *resp = NULL;
242 STACK_OF(CONF_VALUE) *headers = NULL;
243 STACK_OF(OCSP_CERTID) *ids = NULL;
244 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
245 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
246 STACK_OF(X509) *issuers = NULL;
247 X509 *issuer = NULL, *cert = NULL;
248 STACK_OF(X509) *rca_cert = NULL;
249 const EVP_MD *resp_certid_md = NULL;
250 X509 *signer = NULL, *rsigner = NULL;
251 X509_STORE *store = NULL;
252 X509_VERIFY_PARAM *vpm = NULL;
253 const char *CAfile = NULL, *CApath = NULL;
254 char *header, *value;
255 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
256 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
257 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
258 char *rsignfile = NULL, *rkeyfile = NULL;
259 char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
260 char *signfile = NULL, *keyfile = NULL;
261 char *thost = NULL, *tport = NULL, *tpath = NULL;
262 int noCAfile = 0, noCApath = 0;
263 int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
264 int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
265 int req_text = 0, resp_text = 0, ret = 1;
266 int req_timeout = -1;
267 long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
268 unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
271 reqnames = sk_OPENSSL_STRING_new_null();
272 if (reqnames == NULL)
274 ids = sk_OCSP_CERTID_new_null();
277 if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
280 prog = opt_init(argc, argv, ocsp_options);
281 while ((o = opt_next()) != OPT_EOF) {
286 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
290 opt_help(ocsp_options);
296 #ifndef OPENSSL_NO_SOCK
297 req_timeout = atoi(opt_arg());
304 thost = tport = tpath = NULL;
305 if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
306 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
331 case OPT_RESP_NO_CERTS:
332 rflags |= OCSP_NOCERTS;
334 case OPT_RESP_KEY_ID:
335 rflags |= OCSP_RESPID_KEY;
338 sign_flags |= OCSP_NOCERTS;
340 case OPT_NO_SIGNATURE_VERIFY:
341 verify_flags |= OCSP_NOSIGS;
343 case OPT_NO_CERT_VERIFY:
344 verify_flags |= OCSP_NOVERIFY;
347 verify_flags |= OCSP_NOCHAIN;
349 case OPT_NO_CERT_CHECKS:
350 verify_flags |= OCSP_NOCHECKS;
352 case OPT_NO_EXPLICIT:
353 verify_flags |= OCSP_NOEXPLICIT;
355 case OPT_TRUST_OTHER:
356 verify_flags |= OCSP_TRUSTOTHER;
359 verify_flags |= OCSP_NOINTERN;
365 req_text = resp_text = 1;
380 signfile = opt_arg();
383 verify_certfile = opt_arg();
384 verify_flags |= OCSP_TRUSTOTHER;
387 sign_certfile = opt_arg();
389 case OPT_VERIFY_OTHER:
390 verify_certfile = opt_arg();
405 if (!opt_verify(o, vpm))
409 case OPT_VALIDITY_PERIOD:
410 opt_long(opt_arg(), &nsec);
413 opt_long(opt_arg(), &maxage);
428 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
431 if (issuers == NULL) {
432 if ((issuers = sk_X509_new_null()) == NULL)
435 sk_X509_push(issuers, issuer);
439 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
442 if (cert_id_md == NULL)
443 cert_id_md = EVP_sha1();
444 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
446 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
451 if (cert_id_md == NULL)
452 cert_id_md = EVP_sha1();
453 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
455 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
460 ridx_filename = opt_arg();
463 rca_filename = opt_arg();
466 opt_int(opt_arg(), &nmin);
471 opt_int(opt_arg(), &accept_count);
474 ndays = atoi(opt_arg());
477 rsignfile = opt_arg();
480 rkeyfile = opt_arg();
483 rcertfile = opt_arg();
485 case OPT_RMD: /* Response MessageDigest */
486 if (!opt_md(opt_arg(), &rsign_md))
490 if (rsign_sigopts == NULL)
491 rsign_sigopts = sk_OPENSSL_STRING_new_null();
492 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
497 value = strchr(header, '=');
499 BIO_printf(bio_err, "Missing = in header key=value\n");
503 if (!X509V3_add_value(header, value, &headers))
507 resp_certid_md = EVP_get_digestbyname(opt_arg());
508 if (resp_certid_md == NULL)
514 "%s: Digest must be before -cert or -serial\n",
518 if (!opt_md(opt_unknown(), &cert_id_md))
524 multi = atoi(opt_arg());
530 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
534 argc = opt_num_rest();
538 /* Have we anything to do? */
539 if (req == NULL && reqin == NULL
540 && respin == NULL && !(port != NULL && ridx_filename != NULL))
543 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
547 if (req == NULL && (add_nonce != 2))
550 if (req == NULL && reqin != NULL) {
551 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
554 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
557 BIO_printf(bio_err, "Error reading OCSP request\n");
562 if (req == NULL && port != NULL) {
563 acbio = init_responder(port);
568 if (rsignfile != NULL) {
569 if (rkeyfile == NULL)
570 rkeyfile = rsignfile;
571 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
572 if (rsigner == NULL) {
573 BIO_printf(bio_err, "Error loading responder certificate\n");
576 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
577 NULL, "CA certificate"))
579 if (rcertfile != NULL) {
580 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
581 "responder other certificates"))
584 rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
585 "responder private key");
590 if (ridx_filename != NULL
591 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
593 "Responder mode requires certificate, key, and CA.\n");
597 if (ridx_filename != NULL) {
598 rdb = load_index(ridx_filename, NULL);
599 if (rdb == NULL || index_index(rdb) <= 0) {
606 if (multi && acbio != NULL)
608 if (acbio != NULL && req_timeout > 0)
609 signal(SIGALRM, sock_timeout);
613 log_message(LOG_INFO, "waiting for OCSP client connections...");
619 if (index_changed(rdb)) {
620 CA_DB *newrdb = load_index(ridx_filename, NULL);
622 if (newrdb != NULL && index_index(newrdb) > 0) {
627 log_message(LOG_ERR, "error reloading updated index: %s",
634 if (!do_responder(&req, &cbio, acbio, req_timeout))
639 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
641 send_ocsp_response(cbio, resp);
647 && (signfile != NULL || reqout != NULL
648 || host != NULL || add_nonce || ridx_filename != NULL)) {
649 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
653 if (req != NULL && add_nonce) {
654 if (!OCSP_request_add1_nonce(req, NULL, -1))
658 if (signfile != NULL) {
661 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
662 if (signer == NULL) {
663 BIO_printf(bio_err, "Error loading signer certificate\n");
666 if (sign_certfile != NULL) {
667 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
668 "signer certificates"))
671 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
672 "signer private key");
676 if (!OCSP_request_sign
677 (req, signer, key, NULL, sign_other, sign_flags)) {
678 BIO_printf(bio_err, "Error signing OCSP request\n");
683 if (req_text && req != NULL)
684 OCSP_REQUEST_print(out, req, 0);
686 if (reqout != NULL) {
687 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
690 i2d_OCSP_REQUEST_bio(derbio, req);
695 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
696 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
699 send_ocsp_response(cbio, resp);
700 } else if (host != NULL) {
701 # ifndef OPENSSL_NO_SOCK
702 resp = process_responder(req, host, path,
703 port, use_ssl, headers, req_timeout);
708 "Error creating connect BIO - sockets not supported.\n");
711 } else if (respin != NULL) {
712 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
715 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
718 BIO_printf(bio_err, "Error reading OCSP response\n");
728 if (respout != NULL) {
729 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
732 i2d_OCSP_RESPONSE_bio(derbio, resp);
736 i = OCSP_response_status(resp);
737 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
738 BIO_printf(out, "Responder Error: %s (%d)\n",
739 OCSP_response_status_str(i), i);
745 OCSP_RESPONSE_print(out, resp, 0);
747 /* If running as responder don't verify our own response */
749 /* If not unlimited, see if we took all we should. */
750 if (accept_count != -1 && --accept_count <= 0) {
756 OCSP_REQUEST_free(req);
758 OCSP_RESPONSE_free(resp);
762 if (ridx_filename != NULL) {
768 store = setup_verify(CAfile, CApath, noCAfile, noCApath);
773 X509_STORE_set1_param(store, vpm);
774 if (verify_certfile != NULL) {
775 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
776 "validator certificate"))
780 bs = OCSP_response_get1_basic(resp);
782 BIO_printf(bio_err, "Error parsing response\n");
789 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
791 BIO_printf(bio_err, "WARNING: no nonce in response\n");
793 BIO_printf(bio_err, "Nonce Verify error\n");
799 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
800 if (i <= 0 && issuers) {
801 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
806 BIO_printf(bio_err, "Response Verify Failure\n");
807 ERR_print_errors(bio_err);
810 BIO_printf(bio_err, "Response verify OK\n");
814 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
817 ERR_print_errors(bio_err);
819 X509_STORE_free(store);
820 X509_VERIFY_PARAM_free(vpm);
821 sk_OPENSSL_STRING_free(rsign_sigopts);
825 sk_X509_pop_free(issuers, X509_free);
827 sk_X509_pop_free(rca_cert, X509_free);
832 OCSP_REQUEST_free(req);
833 OCSP_RESPONSE_free(resp);
834 OCSP_BASICRESP_free(bs);
835 sk_OPENSSL_STRING_free(reqnames);
836 sk_OCSP_CERTID_free(ids);
837 sk_X509_pop_free(sign_other, X509_free);
838 sk_X509_pop_free(verify_other, X509_free);
839 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
848 log_message(int level, const char *fmt, ...)
856 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
857 syslog(level, "%s", buf);
859 if (level >= LOG_ERR)
860 ERR_print_errors_cb(print_syslog, &level);
864 BIO_printf(bio_err, "%s: ", prog);
865 BIO_vprintf(bio_err, fmt, ap);
866 BIO_printf(bio_err, "\n");
873 static int print_syslog(const char *str, size_t len, void *levPtr)
875 int level = *(int *)levPtr;
876 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
878 syslog(level, "%.*s", ilen, str);
883 static int index_changed(CA_DB *rdb)
887 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
888 if (rdb->dbst.st_mtime != sb.st_mtime
889 || rdb->dbst.st_ctime != sb.st_ctime
890 || rdb->dbst.st_ino != sb.st_ino
891 || rdb->dbst.st_dev != sb.st_dev) {
892 syslog(LOG_INFO, "index file changed, reloading");
899 static void killall(int ret, pid_t *kidpids)
903 for (i = 0; i < multi; ++i)
905 (void)kill(kidpids[i], SIGTERM);
906 OPENSSL_free(kidpids);
911 static int termsig = 0;
913 static void noteterm (int sig)
919 * Loop spawning up to `multi` child processes, only child processes return
920 * from this function. The parent process loops until receiving a termination
921 * signal, kills extant children and exits without returning.
923 static void spawn_loop(void)
925 pid_t *kidpids = NULL;
930 openlog(prog, LOG_PID, LOG_DAEMON);
933 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
937 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
938 for (i = 0; i < multi; ++i)
941 signal(SIGINT, noteterm);
942 signal(SIGTERM, noteterm);
944 while (termsig == 0) {
948 * Wait for a child to replace when we're at the limit.
949 * Slow down if a child exited abnormally or waitpid() < 0
951 while (termsig == 0 && procs >= multi) {
952 if ((fpid = waitpid(-1, &status, 0)) > 0) {
953 for (i = 0; i < procs; ++i) {
954 if (kidpids[i] == fpid) {
961 syslog(LOG_ERR, "fatal: internal error: "
962 "no matching child slot for pid: %ld",
967 if (WIFEXITED(status))
968 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
969 (long)fpid, WEXITSTATUS(status));
970 else if (WIFSIGNALED(status))
971 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
972 (long)fpid, WTERMSIG(status),
974 WCOREDUMP(status) ? " (core dumped)" :
980 } else if (errno != EINTR) {
981 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
988 switch(fpid = fork()) {
990 /* System critically low on memory, pause and try again later */
994 OPENSSL_free(kidpids);
995 signal(SIGINT, SIG_DFL);
996 signal(SIGTERM, SIG_DFL);
999 if (RAND_poll() <= 0) {
1000 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1004 default: /* parent */
1005 for (i = 0; i < multi; ++i) {
1006 if (kidpids[i] == 0) {
1013 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1014 killall(1, kidpids);
1020 /* The loop above can only break on termsig */
1021 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1022 killall(0, kidpids);
1026 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1027 const EVP_MD *cert_id_md, X509 *issuer,
1028 STACK_OF(OCSP_CERTID) *ids)
1032 if (issuer == NULL) {
1033 BIO_printf(bio_err, "No issuer certificate specified\n");
1037 *req = OCSP_REQUEST_new();
1040 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1041 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1043 if (!OCSP_request_add0_id(*req, id))
1048 BIO_printf(bio_err, "Error Creating OCSP request\n");
1052 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1053 const EVP_MD *cert_id_md, X509 *issuer,
1054 STACK_OF(OCSP_CERTID) *ids)
1058 ASN1_BIT_STRING *ikey;
1061 if (issuer == NULL) {
1062 BIO_printf(bio_err, "No issuer certificate specified\n");
1066 *req = OCSP_REQUEST_new();
1069 iname = X509_get_subject_name(issuer);
1070 ikey = X509_get0_pubkey_bitstr(issuer);
1071 sno = s2i_ASN1_INTEGER(NULL, serial);
1073 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1076 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1077 ASN1_INTEGER_free(sno);
1078 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1080 if (!OCSP_request_add0_id(*req, id))
1085 BIO_printf(bio_err, "Error Creating OCSP request\n");
1089 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1090 STACK_OF(OPENSSL_STRING) *names,
1091 STACK_OF(OCSP_CERTID) *ids, long nsec,
1096 int i, status, reason;
1097 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1099 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1100 || !sk_OCSP_CERTID_num(ids))
1103 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1104 id = sk_OCSP_CERTID_value(ids, i);
1105 name = sk_OPENSSL_STRING_value(names, i);
1106 BIO_printf(out, "%s: ", name);
1108 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1109 &rev, &thisupd, &nextupd)) {
1110 BIO_puts(out, "ERROR: No Status found.\n");
1115 * Check validity: if invalid write to output BIO so we know which
1116 * response this refers to.
1118 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1119 BIO_puts(out, "WARNING: Status times invalid.\n");
1120 ERR_print_errors(out);
1122 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1124 BIO_puts(out, "\tThis Update: ");
1125 ASN1_GENERALIZEDTIME_print(out, thisupd);
1126 BIO_puts(out, "\n");
1129 BIO_puts(out, "\tNext Update: ");
1130 ASN1_GENERALIZEDTIME_print(out, nextupd);
1131 BIO_puts(out, "\n");
1134 if (status != V_OCSP_CERTSTATUS_REVOKED)
1138 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1140 BIO_puts(out, "\tRevocation Time: ");
1141 ASN1_GENERALIZEDTIME_print(out, rev);
1142 BIO_puts(out, "\n");
1146 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1147 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1148 EVP_PKEY *rkey, const EVP_MD *rmd,
1149 STACK_OF(OPENSSL_STRING) *sigopts,
1150 STACK_OF(X509) *rother, unsigned long flags,
1151 int nmin, int ndays, int badsig,
1152 const EVP_MD *resp_md)
1154 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1156 OCSP_BASICRESP *bs = NULL;
1158 EVP_MD_CTX *mctx = NULL;
1159 EVP_PKEY_CTX *pkctx = NULL;
1161 id_count = OCSP_request_onereq_count(req);
1163 if (id_count <= 0) {
1165 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1169 bs = OCSP_BASICRESP_new();
1170 thisupd = X509_gmtime_adj(NULL, 0);
1172 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1174 /* Examine each certificate id in the request */
1175 for (i = 0; i < id_count; i++) {
1177 ASN1_INTEGER *serial;
1181 ASN1_OBJECT *cert_id_md_oid;
1182 const EVP_MD *cert_id_md;
1183 OCSP_CERTID *cid_resp_md = NULL;
1185 one = OCSP_request_onereq_get0(req, i);
1186 cid = OCSP_onereq_get0_id(one);
1188 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1190 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1191 if (cert_id_md == NULL) {
1192 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1196 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1197 X509 *ca_cert = sk_X509_value(ca, jj);
1198 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1200 if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1202 if (resp_md != NULL)
1203 cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1205 OCSP_CERTID_free(ca_id);
1207 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1208 inf = lookup_serial(db, serial);
1210 /* at this point, we can have cid be an alias of cid_resp_md */
1211 cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1214 OCSP_basic_add1_status(bs, cid,
1215 V_OCSP_CERTSTATUS_UNKNOWN,
1216 0, NULL, thisupd, nextupd);
1220 OCSP_basic_add1_status(bs, cid,
1221 V_OCSP_CERTSTATUS_UNKNOWN,
1222 0, NULL, thisupd, nextupd);
1223 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1224 OCSP_basic_add1_status(bs, cid,
1225 V_OCSP_CERTSTATUS_GOOD,
1226 0, NULL, thisupd, nextupd);
1227 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1228 ASN1_OBJECT *inst = NULL;
1229 ASN1_TIME *revtm = NULL;
1230 ASN1_GENERALIZEDTIME *invtm = NULL;
1231 OCSP_SINGLERESP *single;
1234 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1235 single = OCSP_basic_add1_status(bs, cid,
1236 V_OCSP_CERTSTATUS_REVOKED,
1237 reason, revtm, thisupd, nextupd);
1239 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1241 else if (inst != NULL)
1242 OCSP_SINGLERESP_add1_ext_i2d(single,
1243 NID_hold_instruction_code, inst,
1245 ASN1_OBJECT_free(inst);
1246 ASN1_TIME_free(revtm);
1247 ASN1_GENERALIZEDTIME_free(invtm);
1249 OCSP_CERTID_free(cid_resp_md);
1252 OCSP_copy_nonce(bs, req);
1254 mctx = EVP_MD_CTX_new();
1255 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1256 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1259 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1260 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1262 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1263 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1264 ERR_print_errors(bio_err);
1265 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1270 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1271 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1276 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1277 corrupt_signature(sig);
1280 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1283 EVP_MD_CTX_free(mctx);
1284 ASN1_TIME_free(thisupd);
1285 ASN1_TIME_free(nextupd);
1286 OCSP_BASICRESP_free(bs);
1289 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1293 char *itmp, *row[DB_NUMBER], **rrow;
1294 for (i = 0; i < DB_NUMBER; i++)
1296 bn = ASN1_INTEGER_to_BN(ser, NULL);
1297 OPENSSL_assert(bn); /* FIXME: should report an error at this
1298 * point and abort */
1300 itmp = OPENSSL_strdup("00");
1302 itmp = BN_bn2hex(bn);
1303 row[DB_serial] = itmp;
1305 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1310 /* Quick and dirty OCSP server: read in and parse input request */
1312 static BIO *init_responder(const char *port)
1314 # ifdef OPENSSL_NO_SOCK
1316 "Error setting up accept BIO - sockets not supported.\n");
1319 BIO *acbio = NULL, *bufbio = NULL;
1321 bufbio = BIO_new(BIO_f_buffer());
1324 acbio = BIO_new(BIO_s_accept());
1326 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1327 || BIO_set_accept_port(acbio, port) < 0) {
1328 log_message(LOG_ERR, "Error setting up accept BIO");
1332 BIO_set_accept_bios(acbio, bufbio);
1334 if (BIO_do_accept(acbio) <= 0) {
1335 log_message(LOG_ERR, "Error starting accept");
1342 BIO_free_all(acbio);
1348 # ifndef OPENSSL_NO_SOCK
1350 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1352 static int urldecode(char *p)
1354 unsigned char *out = (unsigned char *)p;
1355 unsigned char *save = out;
1360 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1361 /* Don't check, can't fail because of ixdigit() call. */
1362 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1363 | OPENSSL_hexchar2int(p[2]);
1370 return (int)(out - save);
1375 static void sock_timeout(int signum)
1377 if (acfd != (int)INVALID_SOCKET)
1378 (void)shutdown(acfd, SHUT_RD);
1382 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1385 # ifdef OPENSSL_NO_SOCK
1389 OCSP_REQUEST *req = NULL;
1390 char inbuf[2048], reqbuf[2048];
1392 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1397 /* Connection loss before accept() is routine, ignore silently */
1398 if (BIO_do_accept(acbio) <= 0)
1401 cbio = BIO_pop(acbio);
1403 client = BIO_get_peer_name(cbio);
1407 (void) BIO_get_fd(cbio, &acfd);
1412 /* Read the request line. */
1413 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1417 if (strncmp(reqbuf, "GET ", 4) == 0) {
1418 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1419 for (p = reqbuf + 4; *p == ' '; ++p)
1422 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1427 /* Splice off the HTTP version identifier. */
1428 for (q = p; *q; q++)
1431 if (strncmp(q, " HTTP/1.", 8) != 0) {
1432 log_message(LOG_INFO,
1433 "Invalid request -- bad HTTP version: %s", client);
1439 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1440 * 'p' was incremented above to point to the first byte *after* the
1441 * leading slash, so with 'GET / ' it is now an empty string.
1448 log_message(LOG_INFO,
1449 "Invalid request -- bad URL encoding: %s", client);
1452 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1453 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1454 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1457 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1458 getbio = BIO_push(b64, getbio);
1459 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1460 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1464 /* Read and skip past the headers. */
1466 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1469 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1474 /* Clear alarm before we close the client socket */
1479 /* Try to read OCSP request */
1480 if (getbio != NULL) {
1481 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1482 BIO_free_all(getbio);
1484 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1488 log_message(LOG_ERR, "Error parsing OCSP request");
1496 acfd = (int)INVALID_SOCKET;
1502 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1505 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1506 "Content-Length: %d\r\n\r\n";
1509 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1510 i2d_OCSP_RESPONSE_bio(cbio, resp);
1511 (void)BIO_flush(cbio);
1515 # ifndef OPENSSL_NO_SOCK
1516 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1518 const STACK_OF(CONF_VALUE) *headers,
1519 OCSP_REQUEST *req, int req_timeout)
1525 OCSP_REQ_CTX *ctx = NULL;
1526 OCSP_RESPONSE *rsp = NULL;
1530 if (req_timeout != -1)
1531 BIO_set_nbio(cbio, 1);
1533 rv = BIO_do_connect(cbio);
1535 if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1536 BIO_puts(bio_err, "Error connecting BIO\n");
1540 if (BIO_get_fd(cbio, &fd) < 0) {
1541 BIO_puts(bio_err, "Can't get connection fd\n");
1545 if (req_timeout != -1 && rv <= 0) {
1547 openssl_fdset(fd, &confds);
1549 tv.tv_sec = req_timeout;
1550 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1552 BIO_puts(bio_err, "Timeout on connect\n");
1557 ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1561 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1562 CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1563 if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1565 if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1569 if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1572 if (!OCSP_REQ_CTX_set1_req(ctx, req))
1576 rv = OCSP_sendreq_nbio(&rsp, ctx);
1579 if (req_timeout == -1)
1582 openssl_fdset(fd, &confds);
1584 tv.tv_sec = req_timeout;
1585 if (BIO_should_read(cbio)) {
1586 rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1587 } else if (BIO_should_write(cbio)) {
1588 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1590 BIO_puts(bio_err, "Unexpected retry condition\n");
1594 BIO_puts(bio_err, "Timeout on request\n");
1598 BIO_puts(bio_err, "Select error\n");
1604 OCSP_REQ_CTX_free(ctx);
1609 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1610 const char *host, const char *path,
1611 const char *port, int use_ssl,
1612 STACK_OF(CONF_VALUE) *headers,
1616 SSL_CTX *ctx = NULL;
1617 OCSP_RESPONSE *resp = NULL;
1619 cbio = BIO_new_connect(host);
1621 BIO_printf(bio_err, "Error creating connect BIO\n");
1625 BIO_set_conn_port(cbio, port);
1628 ctx = SSL_CTX_new(TLS_client_method());
1630 BIO_printf(bio_err, "Error creating SSL context.\n");
1633 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1634 sbio = BIO_new_ssl(ctx, 1);
1635 cbio = BIO_push(sbio, cbio);
1638 resp = query_responder(cbio, host, path, headers, req, req_timeout);
1640 BIO_printf(bio_err, "Error querying OCSP responder\n");