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_SYS_VMS
13 /* So fd_set and friends get properly defined on OpenVMS */
14 # define _XOPEN_SOURCE_EXTENDED
23 /* Needs to be included before the openssl headers */
26 #include "internal/sockets.h"
27 #include <openssl/e_os2.h>
28 #include <openssl/crypto.h>
29 #include <openssl/err.h>
30 #include <openssl/ssl.h>
31 #include <openssl/evp.h>
32 #include <openssl/bn.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/rand.h>
37 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
50 #if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
51 && !defined(OPENSSL_NO_POSIX_IO)
53 # include <sys/types.h>
54 # include <sys/wait.h>
57 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
63 # define LOG_WARNING 1
67 #if defined(OPENSSL_SYS_VXWORKS)
69 int setpgid(pid_t pid, pid_t pgid)
81 /* Maximum leeway in validity period: default 5 minutes */
82 #define MAX_VALIDITY_PERIOD (5 * 60)
84 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
85 const EVP_MD *cert_id_md, X509 *issuer,
86 STACK_OF(OCSP_CERTID) *ids);
87 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
88 const EVP_MD *cert_id_md, X509 *issuer,
89 STACK_OF(OCSP_CERTID) *ids);
90 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
91 STACK_OF(OPENSSL_STRING) *names,
92 STACK_OF(OCSP_CERTID) *ids, long nsec,
94 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
95 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
96 EVP_PKEY *rkey, const EVP_MD *md,
97 STACK_OF(OPENSSL_STRING) *sigopts,
98 STACK_OF(X509) *rother, unsigned long flags,
99 int nmin, int ndays, int badsig,
100 const EVP_MD *resp_md);
102 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
103 static BIO *init_responder(const char *port);
104 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
105 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
106 static void log_message(int level, const char *fmt, ...);
108 static int multi = 0;
111 static int acfd = (int) INVALID_SOCKET;
112 static int index_changed(CA_DB *);
113 static void spawn_loop(void);
114 static int print_syslog(const char *str, size_t len, void *levPtr);
115 static void socket_timeout(int signum);
118 typedef enum OPTION_choice {
119 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
120 OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
121 OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
122 OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
123 OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
124 OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
125 OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
126 OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
127 OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE,
128 OPT_NOCAPATH, OPT_NOCASTORE,
129 OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
130 OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
131 OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
132 OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
137 OPT_MULTI, OPT_PROV_ENUM
140 const OPTIONS ocsp_options[] = {
141 OPT_SECTION("General"),
142 {"help", OPT_HELP, '-', "Display this summary"},
143 {"ignore_err", OPT_IGNORE_ERR, '-',
144 "Ignore error on OCSP request or response and continue running"},
145 {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
146 {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
147 {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
148 {"no-CAfile", OPT_NOCAFILE, '-',
149 "Do not load the default certificates file"},
150 {"no-CApath", OPT_NOCAPATH, '-',
151 "Do not load certificates from the default certificates directory"},
152 {"no-CAstore", OPT_NOCAPATH, '-',
153 "Do not load certificates from the default certificates store"},
155 OPT_SECTION("Responder"),
156 {"timeout", OPT_TIMEOUT, 'p',
157 "Connection timeout (in seconds) to the OCSP responder"},
158 {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
159 "Don't include any certificates in response"},
161 {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
163 {"no_certs", OPT_NO_CERTS, '-',
164 "Don't include any certificates in signed request"},
165 {"badsig", OPT_BADSIG, '-',
166 "Corrupt last byte of loaded OSCP response signature (for test)"},
167 {"CA", OPT_CA, '<', "CA certificate"},
168 {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
169 {"nrequest", OPT_REQUEST, 'p',
170 "Number of requests to accept (default unlimited)"},
171 {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
172 {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
173 {"sign_other", OPT_SIGN_OTHER, '<',
174 "Additional certificates to include in signed request"},
175 {"index", OPT_INDEX, '<', "Certificate status index file"},
176 {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
177 {"rsigner", OPT_RSIGNER, '<',
178 "Responder certificate to sign responses with"},
179 {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
180 {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"},
181 {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
182 {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
183 {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
184 {"header", OPT_HEADER, 's', "key=value header to add"},
185 {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
186 {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
188 OPT_SECTION("Client"),
189 {"url", OPT_URL, 's', "Responder URL"},
190 {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
191 {"port", OPT_PORT, 'p', "Port to run responder on"},
192 {"out", OPT_OUTFILE, '>', "Output filename"},
193 {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
194 {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
195 {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
196 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
197 "Don't check signature on response"},
198 {"resp_key_id", OPT_RESP_KEY_ID, '-',
199 "Identify response by signing certificate key ID"},
200 {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
201 "Don't check signing certificate"},
202 {"text", OPT_TEXT, '-', "Print text form of request and response"},
203 {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
204 {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
205 {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
206 {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
207 "Don't do additional checks on signing certificate"},
208 {"no_explicit", OPT_NO_EXPLICIT, '-',
209 "Do not explicitly check the chain, just verify the root"},
210 {"trust_other", OPT_TRUST_OTHER, '-',
211 "Don't verify additional certificates"},
212 {"no_intern", OPT_NO_INTERN, '-',
213 "Don't search certificates contained in response for signer"},
214 {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
215 {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
216 {"verify_other", OPT_VERIFY_OTHER, '<',
217 "Additional certificates to search for signer"},
218 {"path", OPT_PATH, 's', "Path to use in OCSP request"},
219 {"cert", OPT_CERT, '<', "Certificate to check"},
220 {"serial", OPT_SERIAL, 's', "Serial number to check"},
221 {"validity_period", OPT_VALIDITY_PERIOD, 'u',
222 "Maximum validity discrepancy in seconds"},
223 {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
224 {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
225 {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
226 {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
227 {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
234 int ocsp_main(int argc, char **argv)
236 BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
237 const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
238 STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
241 EVP_PKEY *key = NULL, *rkey = NULL;
242 OCSP_BASICRESP *bs = NULL;
243 OCSP_REQUEST *req = NULL;
244 OCSP_RESPONSE *resp = NULL;
245 STACK_OF(CONF_VALUE) *headers = NULL;
246 STACK_OF(OCSP_CERTID) *ids = NULL;
247 STACK_OF(OPENSSL_STRING) *reqnames = NULL;
248 STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
249 STACK_OF(X509) *issuers = NULL;
250 X509 *issuer = NULL, *cert = NULL;
251 STACK_OF(X509) *rca_cert = NULL;
252 const EVP_MD *resp_certid_md = NULL;
253 X509 *signer = NULL, *rsigner = NULL;
254 X509_STORE *store = NULL;
255 X509_VERIFY_PARAM *vpm = NULL;
256 const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
257 char *header, *value;
258 char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
259 char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
260 char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
261 char *rsignfile = NULL, *rkeyfile = NULL;
262 char *passinarg = NULL, *passin = 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 (!OSSL_HTTP_parse_url(opt_arg(),
310 &host, &port, &path, &use_ssl)) {
311 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
336 case OPT_RESP_NO_CERTS:
337 rflags |= OCSP_NOCERTS;
339 case OPT_RESP_KEY_ID:
340 rflags |= OCSP_RESPID_KEY;
343 sign_flags |= OCSP_NOCERTS;
345 case OPT_NO_SIGNATURE_VERIFY:
346 verify_flags |= OCSP_NOSIGS;
348 case OPT_NO_CERT_VERIFY:
349 verify_flags |= OCSP_NOVERIFY;
352 verify_flags |= OCSP_NOCHAIN;
354 case OPT_NO_CERT_CHECKS:
355 verify_flags |= OCSP_NOCHECKS;
357 case OPT_NO_EXPLICIT:
358 verify_flags |= OCSP_NOEXPLICIT;
360 case OPT_TRUST_OTHER:
361 verify_flags |= OCSP_TRUSTOTHER;
364 verify_flags |= OCSP_NOINTERN;
370 req_text = resp_text = 1;
385 signfile = opt_arg();
388 verify_certfile = opt_arg();
389 verify_flags |= OCSP_TRUSTOTHER;
392 sign_certfile = opt_arg();
394 case OPT_VERIFY_OTHER:
395 verify_certfile = opt_arg();
416 if (!opt_verify(o, vpm))
420 case OPT_VALIDITY_PERIOD:
421 opt_long(opt_arg(), &nsec);
424 opt_long(opt_arg(), &maxage);
439 issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
442 if (issuers == NULL) {
443 if ((issuers = sk_X509_new_null()) == NULL)
446 if (!sk_X509_push(issuers, issuer))
451 cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
454 if (cert_id_md == NULL)
455 cert_id_md = EVP_sha1();
456 if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
458 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
463 if (cert_id_md == NULL)
464 cert_id_md = EVP_sha1();
465 if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
467 if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
472 ridx_filename = opt_arg();
475 rca_filename = opt_arg();
478 opt_int(opt_arg(), &nmin);
483 opt_int(opt_arg(), &accept_count);
486 ndays = atoi(opt_arg());
489 rsignfile = opt_arg();
492 rkeyfile = opt_arg();
495 passinarg = opt_arg();
498 rcertfile = opt_arg();
500 case OPT_RMD: /* Response MessageDigest */
501 if (!opt_md(opt_arg(), &rsign_md))
505 if (rsign_sigopts == NULL)
506 rsign_sigopts = sk_OPENSSL_STRING_new_null();
507 if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
512 value = strchr(header, '=');
514 BIO_printf(bio_err, "Missing = in header key=value\n");
518 if (!X509V3_add_value(header, value, &headers))
522 resp_certid_md = EVP_get_digestbyname(opt_arg());
523 if (resp_certid_md == NULL)
529 "%s: Digest must be before -cert or -serial\n",
533 if (!opt_md(opt_unknown(), &cert_id_md))
539 multi = atoi(opt_arg());
543 if (!opt_provider(o))
549 BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
553 argc = opt_num_rest();
557 /* Have we anything to do? */
558 if (req == NULL && reqin == NULL
559 && respin == NULL && !(port != NULL && ridx_filename != NULL))
562 out = bio_open_default(outfile, 'w', FORMAT_TEXT);
566 if (req == NULL && (add_nonce != 2))
569 if (req == NULL && reqin != NULL) {
570 derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
573 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
576 BIO_printf(bio_err, "Error reading OCSP request\n");
581 if (req == NULL && port != NULL) {
582 acbio = init_responder(port);
587 if (rsignfile != NULL) {
588 if (rkeyfile == NULL)
589 rkeyfile = rsignfile;
590 rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
591 if (rsigner == NULL) {
592 BIO_printf(bio_err, "Error loading responder certificate\n");
595 if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
596 NULL, "CA certificate"))
598 if (rcertfile != NULL) {
599 if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
600 "responder other certificates"))
603 if (!app_passwd(passinarg, NULL, &passin, NULL)) {
604 BIO_printf(bio_err, "Error getting password\n");
607 rkey = load_key(rkeyfile, FORMAT_PEM, 0, passin, NULL,
608 "responder private key");
613 if (ridx_filename != NULL
614 && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
616 "Responder mode requires certificate, key, and CA.\n");
620 if (ridx_filename != NULL) {
621 rdb = load_index(ridx_filename, NULL);
622 if (rdb == NULL || index_index(rdb) <= 0) {
629 if (multi && acbio != NULL)
631 if (acbio != NULL && req_timeout > 0)
632 signal(SIGALRM, socket_timeout);
636 log_message(LOG_INFO, "waiting for OCSP client connections...");
642 if (index_changed(rdb)) {
643 CA_DB *newrdb = load_index(ridx_filename, NULL);
645 if (newrdb != NULL && index_index(newrdb) > 0) {
650 log_message(LOG_ERR, "error reloading updated index: %s",
657 if (!do_responder(&req, &cbio, acbio, req_timeout))
662 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
664 send_ocsp_response(cbio, resp);
670 && (signfile != NULL || reqout != NULL
671 || host != NULL || add_nonce || ridx_filename != NULL)) {
672 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
676 if (req != NULL && add_nonce) {
677 if (!OCSP_request_add1_nonce(req, NULL, -1))
681 if (signfile != NULL) {
684 signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
685 if (signer == NULL) {
686 BIO_printf(bio_err, "Error loading signer certificate\n");
689 if (sign_certfile != NULL) {
690 if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
691 "signer certificates"))
694 key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
695 "signer private key");
699 if (!OCSP_request_sign
700 (req, signer, key, NULL, sign_other, sign_flags)) {
701 BIO_printf(bio_err, "Error signing OCSP request\n");
706 if (req_text && req != NULL)
707 OCSP_REQUEST_print(out, req, 0);
709 if (reqout != NULL) {
710 derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
713 i2d_OCSP_REQUEST_bio(derbio, req);
718 make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
719 rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
722 send_ocsp_response(cbio, resp);
723 } else if (host != NULL) {
724 #ifndef OPENSSL_NO_SOCK
725 resp = process_responder(req, host, path,
726 port, use_ssl, headers, req_timeout);
731 "Error creating connect BIO - sockets not supported.\n");
734 } else if (respin != NULL) {
735 derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
738 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
741 BIO_printf(bio_err, "Error reading OCSP response\n");
751 if (respout != NULL) {
752 derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
755 i2d_OCSP_RESPONSE_bio(derbio, resp);
759 i = OCSP_response_status(resp);
760 if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
761 BIO_printf(out, "Responder Error: %s (%d)\n",
762 OCSP_response_status_str(i), i);
768 OCSP_RESPONSE_print(out, resp, 0);
770 /* If running as responder don't verify our own response */
772 /* If not unlimited, see if we took all we should. */
773 if (accept_count != -1 && --accept_count <= 0) {
779 OCSP_REQUEST_free(req);
781 OCSP_RESPONSE_free(resp);
785 if (ridx_filename != NULL) {
791 store = setup_verify(CAfile, noCAfile, CApath, noCApath,
797 X509_STORE_set1_param(store, vpm);
798 if (verify_certfile != NULL) {
799 if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
800 "validator certificate"))
804 bs = OCSP_response_get1_basic(resp);
806 BIO_printf(bio_err, "Error parsing response\n");
813 if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
815 BIO_printf(bio_err, "WARNING: no nonce in response\n");
817 BIO_printf(bio_err, "Nonce Verify error\n");
823 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
824 if (i <= 0 && issuers) {
825 i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
830 BIO_printf(bio_err, "Response Verify Failure\n");
831 ERR_print_errors(bio_err);
834 BIO_printf(bio_err, "Response verify OK\n");
838 print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
841 ERR_print_errors(bio_err);
843 X509_STORE_free(store);
844 X509_VERIFY_PARAM_free(vpm);
845 sk_OPENSSL_STRING_free(rsign_sigopts);
849 sk_X509_pop_free(issuers, X509_free);
851 sk_X509_pop_free(rca_cert, X509_free);
856 OCSP_REQUEST_free(req);
857 OCSP_RESPONSE_free(resp);
858 OCSP_BASICRESP_free(bs);
859 sk_OPENSSL_STRING_free(reqnames);
860 sk_OCSP_CERTID_free(ids);
861 sk_X509_pop_free(sign_other, X509_free);
862 sk_X509_pop_free(verify_other, X509_free);
863 sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
872 log_message(int level, const char *fmt, ...)
880 if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
881 syslog(level, "%s", buf);
883 if (level >= LOG_ERR)
884 ERR_print_errors_cb(print_syslog, &level);
888 BIO_printf(bio_err, "%s: ", prog);
889 BIO_vprintf(bio_err, fmt, ap);
890 BIO_printf(bio_err, "\n");
897 static int print_syslog(const char *str, size_t len, void *levPtr)
899 int level = *(int *)levPtr;
900 int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
902 syslog(level, "%.*s", ilen, str);
907 static int index_changed(CA_DB *rdb)
911 if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
912 if (rdb->dbst.st_mtime != sb.st_mtime
913 || rdb->dbst.st_ctime != sb.st_ctime
914 || rdb->dbst.st_ino != sb.st_ino
915 || rdb->dbst.st_dev != sb.st_dev) {
916 syslog(LOG_INFO, "index file changed, reloading");
923 static void killall(int ret, pid_t *kidpids)
927 for (i = 0; i < multi; ++i)
929 (void)kill(kidpids[i], SIGTERM);
930 OPENSSL_free(kidpids);
935 static int termsig = 0;
937 static void noteterm (int sig)
943 * Loop spawning up to `multi` child processes, only child processes return
944 * from this function. The parent process loops until receiving a termination
945 * signal, kills extant children and exits without returning.
947 static void spawn_loop(void)
949 pid_t *kidpids = NULL;
954 openlog(prog, LOG_PID, LOG_DAEMON);
957 syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
961 kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
962 for (i = 0; i < multi; ++i)
965 signal(SIGINT, noteterm);
966 signal(SIGTERM, noteterm);
968 while (termsig == 0) {
972 * Wait for a child to replace when we're at the limit.
973 * Slow down if a child exited abnormally or waitpid() < 0
975 while (termsig == 0 && procs >= multi) {
976 if ((fpid = waitpid(-1, &status, 0)) > 0) {
977 for (i = 0; i < procs; ++i) {
978 if (kidpids[i] == fpid) {
985 syslog(LOG_ERR, "fatal: internal error: "
986 "no matching child slot for pid: %ld",
991 if (WIFEXITED(status))
992 syslog(LOG_WARNING, "child process: %ld, exit status: %d",
993 (long)fpid, WEXITSTATUS(status));
994 else if (WIFSIGNALED(status))
995 syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
996 (long)fpid, WTERMSIG(status),
998 WCOREDUMP(status) ? " (core dumped)" :
1004 } else if (errno != EINTR) {
1005 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
1006 killall(1, kidpids);
1012 switch(fpid = fork()) {
1013 case -1: /* error */
1014 /* System critically low on memory, pause and try again later */
1018 OPENSSL_free(kidpids);
1019 signal(SIGINT, SIG_DFL);
1020 signal(SIGTERM, SIG_DFL);
1023 if (RAND_poll() <= 0) {
1024 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1028 default: /* parent */
1029 for (i = 0; i < multi; ++i) {
1030 if (kidpids[i] == 0) {
1037 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1038 killall(1, kidpids);
1044 /* The loop above can only break on termsig */
1045 syslog(LOG_INFO, "terminating on signal: %d", termsig);
1046 killall(0, kidpids);
1050 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1051 const EVP_MD *cert_id_md, X509 *issuer,
1052 STACK_OF(OCSP_CERTID) *ids)
1056 if (issuer == NULL) {
1057 BIO_printf(bio_err, "No issuer certificate specified\n");
1061 *req = OCSP_REQUEST_new();
1064 id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1065 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1067 if (!OCSP_request_add0_id(*req, id))
1072 BIO_printf(bio_err, "Error Creating OCSP request\n");
1076 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1077 const EVP_MD *cert_id_md, X509 *issuer,
1078 STACK_OF(OCSP_CERTID) *ids)
1081 const X509_NAME *iname;
1082 ASN1_BIT_STRING *ikey;
1085 if (issuer == NULL) {
1086 BIO_printf(bio_err, "No issuer certificate specified\n");
1090 *req = OCSP_REQUEST_new();
1093 iname = X509_get_subject_name(issuer);
1094 ikey = X509_get0_pubkey_bitstr(issuer);
1095 sno = s2i_ASN1_INTEGER(NULL, serial);
1097 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1100 id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1101 ASN1_INTEGER_free(sno);
1102 if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1104 if (!OCSP_request_add0_id(*req, id))
1109 BIO_printf(bio_err, "Error Creating OCSP request\n");
1113 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1114 STACK_OF(OPENSSL_STRING) *names,
1115 STACK_OF(OCSP_CERTID) *ids, long nsec,
1120 int i, status, reason;
1121 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1123 if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1124 || !sk_OCSP_CERTID_num(ids))
1127 for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1128 id = sk_OCSP_CERTID_value(ids, i);
1129 name = sk_OPENSSL_STRING_value(names, i);
1130 BIO_printf(out, "%s: ", name);
1132 if (!OCSP_resp_find_status(bs, id, &status, &reason,
1133 &rev, &thisupd, &nextupd)) {
1134 BIO_puts(out, "ERROR: No Status found.\n");
1139 * Check validity: if invalid write to output BIO so we know which
1140 * response this refers to.
1142 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1143 BIO_puts(out, "WARNING: Status times invalid.\n");
1144 ERR_print_errors(out);
1146 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1148 BIO_puts(out, "\tThis Update: ");
1149 ASN1_GENERALIZEDTIME_print(out, thisupd);
1150 BIO_puts(out, "\n");
1153 BIO_puts(out, "\tNext Update: ");
1154 ASN1_GENERALIZEDTIME_print(out, nextupd);
1155 BIO_puts(out, "\n");
1158 if (status != V_OCSP_CERTSTATUS_REVOKED)
1162 BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1164 BIO_puts(out, "\tRevocation Time: ");
1165 ASN1_GENERALIZEDTIME_print(out, rev);
1166 BIO_puts(out, "\n");
1170 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1171 CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1172 EVP_PKEY *rkey, const EVP_MD *rmd,
1173 STACK_OF(OPENSSL_STRING) *sigopts,
1174 STACK_OF(X509) *rother, unsigned long flags,
1175 int nmin, int ndays, int badsig,
1176 const EVP_MD *resp_md)
1178 ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1180 OCSP_BASICRESP *bs = NULL;
1182 EVP_MD_CTX *mctx = NULL;
1183 EVP_PKEY_CTX *pkctx = NULL;
1185 id_count = OCSP_request_onereq_count(req);
1187 if (id_count <= 0) {
1189 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1193 bs = OCSP_BASICRESP_new();
1194 thisupd = X509_gmtime_adj(NULL, 0);
1196 nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1198 /* Examine each certificate id in the request */
1199 for (i = 0; i < id_count; i++) {
1201 ASN1_INTEGER *serial;
1205 ASN1_OBJECT *cert_id_md_oid;
1206 const EVP_MD *cert_id_md;
1207 OCSP_CERTID *cid_resp_md = NULL;
1209 one = OCSP_request_onereq_get0(req, i);
1210 cid = OCSP_onereq_get0_id(one);
1212 OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1214 cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1215 if (cert_id_md == NULL) {
1216 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1220 for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1221 X509 *ca_cert = sk_X509_value(ca, jj);
1222 OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1224 if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1226 if (resp_md != NULL)
1227 cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1229 OCSP_CERTID_free(ca_id);
1231 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1232 inf = lookup_serial(db, serial);
1234 /* at this point, we can have cid be an alias of cid_resp_md */
1235 cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1238 OCSP_basic_add1_status(bs, cid,
1239 V_OCSP_CERTSTATUS_UNKNOWN,
1240 0, NULL, thisupd, nextupd);
1244 OCSP_basic_add1_status(bs, cid,
1245 V_OCSP_CERTSTATUS_UNKNOWN,
1246 0, NULL, thisupd, nextupd);
1247 } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1248 OCSP_basic_add1_status(bs, cid,
1249 V_OCSP_CERTSTATUS_GOOD,
1250 0, NULL, thisupd, nextupd);
1251 } else if (inf[DB_type][0] == DB_TYPE_REV) {
1252 ASN1_OBJECT *inst = NULL;
1253 ASN1_TIME *revtm = NULL;
1254 ASN1_GENERALIZEDTIME *invtm = NULL;
1255 OCSP_SINGLERESP *single;
1258 unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1259 single = OCSP_basic_add1_status(bs, cid,
1260 V_OCSP_CERTSTATUS_REVOKED,
1261 reason, revtm, thisupd, nextupd);
1263 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1265 else if (inst != NULL)
1266 OCSP_SINGLERESP_add1_ext_i2d(single,
1267 NID_hold_instruction_code, inst,
1269 ASN1_OBJECT_free(inst);
1270 ASN1_TIME_free(revtm);
1271 ASN1_GENERALIZEDTIME_free(invtm);
1273 OCSP_CERTID_free(cid_resp_md);
1276 OCSP_copy_nonce(bs, req);
1278 mctx = EVP_MD_CTX_new();
1279 if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1280 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1283 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1284 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1286 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1287 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1288 ERR_print_errors(bio_err);
1289 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1294 if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1295 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1300 const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1301 corrupt_signature(sig);
1304 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1307 EVP_MD_CTX_free(mctx);
1308 ASN1_TIME_free(thisupd);
1309 ASN1_TIME_free(nextupd);
1310 OCSP_BASICRESP_free(bs);
1313 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1317 char *itmp, *row[DB_NUMBER], **rrow;
1318 for (i = 0; i < DB_NUMBER; i++)
1320 bn = ASN1_INTEGER_to_BN(ser, NULL);
1321 OPENSSL_assert(bn); /* FIXME: should report an error at this
1322 * point and abort */
1324 itmp = OPENSSL_strdup("00");
1326 itmp = BN_bn2hex(bn);
1327 row[DB_serial] = itmp;
1329 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1334 /* Quick and dirty OCSP server: read in and parse input request */
1336 static BIO *init_responder(const char *port)
1338 #ifdef OPENSSL_NO_SOCK
1340 "Error setting up accept BIO - sockets not supported.\n");
1343 BIO *acbio = NULL, *bufbio = NULL;
1345 bufbio = BIO_new(BIO_f_buffer());
1348 acbio = BIO_new(BIO_s_accept());
1350 || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1351 || BIO_set_accept_port(acbio, port) < 0) {
1352 log_message(LOG_ERR, "Error setting up accept BIO");
1356 BIO_set_accept_bios(acbio, bufbio);
1358 if (BIO_do_accept(acbio) <= 0) {
1359 log_message(LOG_ERR, "Error starting accept");
1366 BIO_free_all(acbio);
1372 #ifndef OPENSSL_NO_SOCK
1374 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1376 static int urldecode(char *p)
1378 unsigned char *out = (unsigned char *)p;
1379 unsigned char *save = out;
1384 else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1385 /* Don't check, can't fail because of ixdigit() call. */
1386 *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1387 | OPENSSL_hexchar2int(p[2]);
1394 return (int)(out - save);
1399 static void socket_timeout(int signum)
1401 if (acfd != (int)INVALID_SOCKET)
1402 (void)shutdown(acfd, SHUT_RD);
1406 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1409 #ifdef OPENSSL_NO_SOCK
1413 OCSP_REQUEST *req = NULL;
1414 char inbuf[2048], reqbuf[2048];
1416 BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1421 /* Connection loss before accept() is routine, ignore silently */
1422 if (BIO_do_accept(acbio) <= 0)
1425 cbio = BIO_pop(acbio);
1427 client = BIO_get_peer_name(cbio);
1431 (void) BIO_get_fd(cbio, &acfd);
1436 /* Read the request line. */
1437 len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1441 if (strncmp(reqbuf, "GET ", 4) == 0) {
1442 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1443 for (p = reqbuf + 4; *p == ' '; ++p)
1446 log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1451 /* Splice off the HTTP version identifier. */
1452 for (q = p; *q; q++)
1455 if (strncmp(q, " HTTP/1.", 8) != 0) {
1456 log_message(LOG_INFO,
1457 "Invalid request -- bad HTTP version: %s", client);
1463 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1464 * 'p' was incremented above to point to the first byte *after* the
1465 * leading slash, so with 'GET / ' it is now an empty string.
1472 log_message(LOG_INFO,
1473 "Invalid request -- bad URL encoding: %s", client);
1476 if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1477 || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1478 log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1481 BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1482 getbio = BIO_push(b64, getbio);
1483 } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1484 log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1488 /* Read and skip past the headers. */
1490 len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1493 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1498 /* Clear alarm before we close the client socket */
1503 /* Try to read OCSP request */
1504 if (getbio != NULL) {
1505 req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1506 BIO_free_all(getbio);
1508 req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1512 log_message(LOG_ERR, "Error parsing OCSP request");
1520 acfd = (int)INVALID_SOCKET;
1526 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1529 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1530 "Content-Length: %d\r\n\r\n";
1533 BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1534 i2d_OCSP_RESPONSE_bio(cbio, resp);
1535 (void)BIO_flush(cbio);
1539 #ifndef OPENSSL_NO_SOCK
1540 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1541 const char *host, const char *path,
1542 const char *port, int use_ssl,
1543 STACK_OF(CONF_VALUE) *headers,
1546 SSL_CTX *ctx = NULL;
1547 OCSP_RESPONSE *resp = NULL;
1550 ctx = SSL_CTX_new(TLS_client_method());
1552 BIO_printf(bio_err, "Error creating SSL context.\n");
1555 SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1558 resp = (OCSP_RESPONSE *)
1559 app_http_post_asn1(host, port, path, NULL, NULL /* no proxy used */,
1560 ctx, headers, "application/ocsp-request",
1561 (ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST),
1562 req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE));
1565 BIO_printf(bio_err, "Error querying OCSP responder\n");