Implement multi-process OCSP responder.
[openssl.git] / apps / ocsp.c
1 /*
2  * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/opensslconf.h>
11
12 #ifdef OPENSSL_NO_OCSP
13 NON_EMPTY_TRANSLATION_UNIT
14 #else
15 # ifdef OPENSSL_SYS_VMS
16 #  define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
17                                  * on OpenVMS */
18 # endif
19
20 # include <stdio.h>
21 # include <stdlib.h>
22 # include <string.h>
23 # include <time.h>
24 # include <ctype.h>
25
26 /* Needs to be included before the openssl headers */
27 # include "apps.h"
28 # include "progs.h"
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>
38
39 # if defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_NO_SOCK)
40 #  define OCSP_DAEMON
41 #  include <sys/types.h>
42 #  include <sys/wait.h>
43 #  include <syslog.h>
44 #  include <signal.h>
45 #  define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
46 # else
47 #  undef LOG_INFO
48 #  undef LOG_WARNING
49 #  undef LOG_ERR
50 #  define LOG_INFO      0
51 #  define LOG_WARNING   1
52 #  define LOG_ERR       2
53 # endif
54
55 /* Maximum leeway in validity period: default 5 minutes */
56 # define MAX_VALIDITY_PERIOD    (5 * 60)
57
58 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
59                          const EVP_MD *cert_id_md, X509 *issuer,
60                          STACK_OF(OCSP_CERTID) *ids);
61 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
62                            const EVP_MD *cert_id_md, X509 *issuer,
63                            STACK_OF(OCSP_CERTID) *ids);
64 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
65                               STACK_OF(OPENSSL_STRING) *names,
66                               STACK_OF(OCSP_CERTID) *ids, long nsec,
67                               long maxage);
68 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
69                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
70                               EVP_PKEY *rkey, const EVP_MD *md,
71                               STACK_OF(OPENSSL_STRING) *sigopts,
72                               STACK_OF(X509) *rother, unsigned long flags,
73                               int nmin, int ndays, int badsig);
74
75 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
76 static BIO *init_responder(const char *port);
77 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
78 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
79 static void log_message(int level, const char *fmt, ...);
80 static char *prog;
81 static int multi = 0;
82
83 # ifdef OCSP_DAEMON
84 static int acfd = (int) INVALID_SOCKET;
85 static int index_changed(CA_DB *);
86 static void spawn_loop(void);
87 static int print_syslog(const char *str, size_t len, void *levPtr);
88 static void sock_timeout(int signum);
89 # endif
90
91 # ifndef OPENSSL_NO_SOCK
92 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
93                                       const char *path,
94                                       const STACK_OF(CONF_VALUE) *headers,
95                                       OCSP_REQUEST *req, int req_timeout);
96 # endif
97
98 typedef enum OPTION_choice {
99     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
100     OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
101     OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
102     OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
103     OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
104     OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
105     OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
106     OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
107     OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH,
108     OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
109     OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
110     OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
111     OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
112     OPT_V_ENUM,
113     OPT_MD,
114     OPT_MULTI
115 } OPTION_CHOICE;
116
117 const OPTIONS ocsp_options[] = {
118     {"help", OPT_HELP, '-', "Display this summary"},
119     {"out", OPT_OUTFILE, '>', "Output filename"},
120     {"timeout", OPT_TIMEOUT, 'p',
121      "Connection timeout (in seconds) to the OCSP responder"},
122     {"url", OPT_URL, 's', "Responder URL"},
123     {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
124     {"port", OPT_PORT, 'p', "Port to run responder on"},
125     {"ignore_err", OPT_IGNORE_ERR, '-',
126      "Ignore error on OCSP request or response and continue running"},
127     {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
128     {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
129     {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
130     {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
131      "Don't include any certificates in response"},
132     {"resp_key_id", OPT_RESP_KEY_ID, '-',
133      "Identify response by signing certificate key ID"},
134 # ifdef OCSP_DAEMON
135     {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
136 # endif
137     {"no_certs", OPT_NO_CERTS, '-',
138      "Don't include any certificates in signed request"},
139     {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
140      "Don't check signature on response"},
141     {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
142      "Don't check signing certificate"},
143     {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
144     {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
145      "Don't do additional checks on signing certificate"},
146     {"no_explicit", OPT_NO_EXPLICIT, '-',
147      "Do not explicitly check the chain, just verify the root"},
148     {"trust_other", OPT_TRUST_OTHER, '-',
149      "Don't verify additional certificates"},
150     {"no_intern", OPT_NO_INTERN, '-',
151      "Don't search certificates contained in response for signer"},
152     {"badsig", OPT_BADSIG, '-',
153         "Corrupt last byte of loaded OSCP response signature (for test)"},
154     {"text", OPT_TEXT, '-', "Print text form of request and response"},
155     {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
156     {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
157     {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
158     {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
159     {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
160     {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
161     {"sign_other", OPT_SIGN_OTHER, '<',
162      "Additional certificates to include in signed request"},
163     {"verify_other", OPT_VERIFY_OTHER, '<',
164      "Additional certificates to search for signer"},
165     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
166     {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
167     {"no-CAfile", OPT_NOCAFILE, '-',
168      "Do not load the default certificates file"},
169     {"no-CApath", OPT_NOCAPATH, '-',
170      "Do not load certificates from the default certificates directory"},
171     {"validity_period", OPT_VALIDITY_PERIOD, 'u',
172      "Maximum validity discrepancy in seconds"},
173     {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
174     {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
175     {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
176     {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
177     {"path", OPT_PATH, 's', "Path to use in OCSP request"},
178     {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
179     {"cert", OPT_CERT, '<', "Certificate to check"},
180     {"serial", OPT_SERIAL, 's', "Serial number to check"},
181     {"index", OPT_INDEX, '<', "Certificate status index file"},
182     {"CA", OPT_CA, '<', "CA certificate"},
183     {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
184     {"nrequest", OPT_REQUEST, 'p',
185      "Number of requests to accept (default unlimited)"},
186     {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
187     {"rsigner", OPT_RSIGNER, '<',
188      "Responder certificate to sign responses with"},
189     {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
190     {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
191     {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
192     {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
193     {"header", OPT_HEADER, 's', "key=value header to add"},
194     {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
195     OPT_V_OPTIONS,
196     {NULL}
197 };
198
199 int ocsp_main(int argc, char **argv)
200 {
201     BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
202     const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
203     STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
204     int trailing_md = 0;
205     CA_DB *rdb = NULL;
206     EVP_PKEY *key = NULL, *rkey = NULL;
207     OCSP_BASICRESP *bs = NULL;
208     OCSP_REQUEST *req = NULL;
209     OCSP_RESPONSE *resp = NULL;
210     STACK_OF(CONF_VALUE) *headers = NULL;
211     STACK_OF(OCSP_CERTID) *ids = NULL;
212     STACK_OF(OPENSSL_STRING) *reqnames = NULL;
213     STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
214     STACK_OF(X509) *issuers = NULL;
215     X509 *issuer = NULL, *cert = NULL;
216     STACK_OF(X509) *rca_cert = NULL;
217     X509 *signer = NULL, *rsigner = NULL;
218     X509_STORE *store = NULL;
219     X509_VERIFY_PARAM *vpm = NULL;
220     const char *CAfile = NULL, *CApath = NULL;
221     char *header, *value;
222     char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
223     char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
224     char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
225     char *rsignfile = NULL, *rkeyfile = NULL;
226     char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
227     char *signfile = NULL, *keyfile = NULL;
228     char *thost = NULL, *tport = NULL, *tpath = NULL;
229     int noCAfile = 0, noCApath = 0;
230     int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
231     int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
232     int req_text = 0, resp_text = 0, ret = 1;
233 # ifndef OPENSSL_NO_SOCK
234     int req_timeout = -1;
235 # endif
236     long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
237     unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
238     OPTION_CHOICE o;
239
240     reqnames = sk_OPENSSL_STRING_new_null();
241     if (reqnames == NULL)
242         goto end;
243     ids = sk_OCSP_CERTID_new_null();
244     if (ids == NULL)
245         goto end;
246     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
247         return 1;
248
249     prog = opt_init(argc, argv, ocsp_options);
250     while ((o = opt_next()) != OPT_EOF) {
251         switch (o) {
252         case OPT_EOF:
253         case OPT_ERR:
254  opthelp:
255             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
256             goto end;
257         case OPT_HELP:
258             ret = 0;
259             opt_help(ocsp_options);
260             goto end;
261         case OPT_OUTFILE:
262             outfile = opt_arg();
263             break;
264         case OPT_TIMEOUT:
265 #ifndef OPENSSL_NO_SOCK
266             req_timeout = atoi(opt_arg());
267 #endif
268             break;
269         case OPT_URL:
270             OPENSSL_free(thost);
271             OPENSSL_free(tport);
272             OPENSSL_free(tpath);
273             thost = tport = tpath = NULL;
274             if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
275                 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
276                 goto end;
277             }
278             thost = host;
279             tport = port;
280             tpath = path;
281             break;
282         case OPT_HOST:
283             host = opt_arg();
284             break;
285         case OPT_PORT:
286             port = opt_arg();
287             break;
288         case OPT_IGNORE_ERR:
289             ignore_err = 1;
290             break;
291         case OPT_NOVERIFY:
292             noverify = 1;
293             break;
294         case OPT_NONCE:
295             add_nonce = 2;
296             break;
297         case OPT_NO_NONCE:
298             add_nonce = 0;
299             break;
300         case OPT_RESP_NO_CERTS:
301             rflags |= OCSP_NOCERTS;
302             break;
303         case OPT_RESP_KEY_ID:
304             rflags |= OCSP_RESPID_KEY;
305             break;
306         case OPT_NO_CERTS:
307             sign_flags |= OCSP_NOCERTS;
308             break;
309         case OPT_NO_SIGNATURE_VERIFY:
310             verify_flags |= OCSP_NOSIGS;
311             break;
312         case OPT_NO_CERT_VERIFY:
313             verify_flags |= OCSP_NOVERIFY;
314             break;
315         case OPT_NO_CHAIN:
316             verify_flags |= OCSP_NOCHAIN;
317             break;
318         case OPT_NO_CERT_CHECKS:
319             verify_flags |= OCSP_NOCHECKS;
320             break;
321         case OPT_NO_EXPLICIT:
322             verify_flags |= OCSP_NOEXPLICIT;
323             break;
324         case OPT_TRUST_OTHER:
325             verify_flags |= OCSP_TRUSTOTHER;
326             break;
327         case OPT_NO_INTERN:
328             verify_flags |= OCSP_NOINTERN;
329             break;
330         case OPT_BADSIG:
331             badsig = 1;
332             break;
333         case OPT_TEXT:
334             req_text = resp_text = 1;
335             break;
336         case OPT_REQ_TEXT:
337             req_text = 1;
338             break;
339         case OPT_RESP_TEXT:
340             resp_text = 1;
341             break;
342         case OPT_REQIN:
343             reqin = opt_arg();
344             break;
345         case OPT_RESPIN:
346             respin = opt_arg();
347             break;
348         case OPT_SIGNER:
349             signfile = opt_arg();
350             break;
351         case OPT_VAFILE:
352             verify_certfile = opt_arg();
353             verify_flags |= OCSP_TRUSTOTHER;
354             break;
355         case OPT_SIGN_OTHER:
356             sign_certfile = opt_arg();
357             break;
358         case OPT_VERIFY_OTHER:
359             verify_certfile = opt_arg();
360             break;
361         case OPT_CAFILE:
362             CAfile = opt_arg();
363             break;
364         case OPT_CAPATH:
365             CApath = opt_arg();
366             break;
367         case OPT_NOCAFILE:
368             noCAfile = 1;
369             break;
370         case OPT_NOCAPATH:
371             noCApath = 1;
372             break;
373         case OPT_V_CASES:
374             if (!opt_verify(o, vpm))
375                 goto end;
376             vpmtouched++;
377             break;
378         case OPT_VALIDITY_PERIOD:
379             opt_long(opt_arg(), &nsec);
380             break;
381         case OPT_STATUS_AGE:
382             opt_long(opt_arg(), &maxage);
383             break;
384         case OPT_SIGNKEY:
385             keyfile = opt_arg();
386             break;
387         case OPT_REQOUT:
388             reqout = opt_arg();
389             break;
390         case OPT_RESPOUT:
391             respout = opt_arg();
392             break;
393         case OPT_PATH:
394             path = opt_arg();
395             break;
396         case OPT_ISSUER:
397             issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
398             if (issuer == NULL)
399                 goto end;
400             if (issuers == NULL) {
401                 if ((issuers = sk_X509_new_null()) == NULL)
402                     goto end;
403             }
404             sk_X509_push(issuers, issuer);
405             break;
406         case OPT_CERT:
407             X509_free(cert);
408             cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
409             if (cert == NULL)
410                 goto end;
411             if (cert_id_md == NULL)
412                 cert_id_md = EVP_sha1();
413             if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
414                 goto end;
415             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
416                 goto end;
417             trailing_md = 0;
418             break;
419         case OPT_SERIAL:
420             if (cert_id_md == NULL)
421                 cert_id_md = EVP_sha1();
422             if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
423                 goto end;
424             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
425                 goto end;
426             trailing_md = 0;
427             break;
428         case OPT_INDEX:
429             ridx_filename = opt_arg();
430             break;
431         case OPT_CA:
432             rca_filename = opt_arg();
433             break;
434         case OPT_NMIN:
435             opt_int(opt_arg(), &nmin);
436             if (ndays == -1)
437                 ndays = 0;
438             break;
439         case OPT_REQUEST:
440             opt_int(opt_arg(), &accept_count);
441             break;
442         case OPT_NDAYS:
443             ndays = atoi(opt_arg());
444             break;
445         case OPT_RSIGNER:
446             rsignfile = opt_arg();
447             break;
448         case OPT_RKEY:
449             rkeyfile = opt_arg();
450             break;
451         case OPT_ROTHER:
452             rcertfile = opt_arg();
453             break;
454         case OPT_RMD:   /* Response MessageDigest */
455             if (!opt_md(opt_arg(), &rsign_md))
456                 goto end;
457             break;
458         case OPT_RSIGOPT:
459             if (rsign_sigopts == NULL)
460                 rsign_sigopts = sk_OPENSSL_STRING_new_null();
461             if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
462                 goto end;
463             break;
464         case OPT_HEADER:
465             header = opt_arg();
466             value = strchr(header, '=');
467             if (value == NULL) {
468                 BIO_printf(bio_err, "Missing = in header key=value\n");
469                 goto opthelp;
470             }
471             *value++ = '\0';
472             if (!X509V3_add_value(header, value, &headers))
473                 goto end;
474             break;
475         case OPT_MD:
476             if (trailing_md) {
477                 BIO_printf(bio_err,
478                            "%s: Digest must be before -cert or -serial\n",
479                            prog);
480                 goto opthelp;
481             }
482             if (!opt_md(opt_unknown(), &cert_id_md))
483                 goto opthelp;
484             trailing_md = 1;
485             break;
486 # ifdef OCSP_DAEMON
487         case OPT_MULTI:
488             multi = atoi(opt_arg());
489             break;
490 # endif
491         }
492     }
493     if (trailing_md) {
494         BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
495                    prog);
496         goto opthelp;
497     }
498     argc = opt_num_rest();
499     if (argc != 0)
500         goto opthelp;
501
502     /* Have we anything to do? */
503     if (req == NULL && reqin == NULL
504         && respin == NULL && !(port != NULL && ridx_filename != NULL))
505         goto opthelp;
506
507     out = bio_open_default(outfile, 'w', FORMAT_TEXT);
508     if (out == NULL)
509         goto end;
510
511     if (req == NULL && (add_nonce != 2))
512         add_nonce = 0;
513
514     if (req == NULL && reqin != NULL) {
515         derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
516         if (derbio == NULL)
517             goto end;
518         req = d2i_OCSP_REQUEST_bio(derbio, NULL);
519         BIO_free(derbio);
520         if (req == NULL) {
521             BIO_printf(bio_err, "Error reading OCSP request\n");
522             goto end;
523         }
524     }
525
526     if (req == NULL && port != NULL) {
527         acbio = init_responder(port);
528         if (acbio == NULL)
529             goto end;
530     }
531
532     if (rsignfile != NULL) {
533         if (rkeyfile == NULL)
534             rkeyfile = rsignfile;
535         rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
536         if (rsigner == NULL) {
537             BIO_printf(bio_err, "Error loading responder certificate\n");
538             goto end;
539         }
540         if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
541                         NULL, "CA certificate"))
542             goto end;
543         if (rcertfile != NULL) {
544             if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
545                             "responder other certificates"))
546                 goto end;
547         }
548         rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
549                         "responder private key");
550         if (rkey == NULL)
551             goto end;
552     }
553
554     if (ridx_filename != NULL
555         && (rkey != NULL || rsigner != NULL || rca_cert != NULL)) {
556         BIO_printf(bio_err,
557                    "Responder mode requires certificate, key, and CA.\n");
558         goto end;
559     }
560
561     if (ridx_filename != NULL) {
562         rdb = load_index(ridx_filename, NULL);
563         if (rdb == NULL || !index_index(rdb)) {
564             ret = 1;
565             goto end;
566         }
567     }
568
569 # ifdef OCSP_DAEMON
570     if (multi && acbio != NULL)
571         spawn_loop();
572     if (acbio != NULL && req_timeout > 0)
573         signal(SIGALRM, sock_timeout);
574 #endif
575
576     if (acbio != NULL)
577         log_message(LOG_INFO, "waiting for OCSP client connections...");
578
579 redo_accept:
580
581     if (acbio != NULL) {
582 # ifdef OCSP_DAEMON
583         if (index_changed(rdb)) {
584             CA_DB *newrdb = load_index(ridx_filename, NULL);
585
586             if (newrdb != NULL) {
587                 free_index(rdb);
588                 rdb = newrdb;
589             } else {
590                 log_message(LOG_ERR, "error reloading updated index: %s",
591                             ridx_filename);
592             }
593         }
594 # endif
595
596         req = NULL;
597         if (!do_responder(&req, &cbio, acbio, req_timeout))
598             goto redo_accept;
599
600         if (req == NULL) {
601             resp =
602                 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
603                                      NULL);
604             send_ocsp_response(cbio, resp);
605             goto done_resp;
606         }
607     }
608
609     if (req == NULL
610         && (signfile != NULL || reqout != NULL
611             || host != NULL || add_nonce || ridx_filename != NULL)) {
612         BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
613         goto end;
614     }
615
616     if (req != NULL && add_nonce)
617         OCSP_request_add1_nonce(req, NULL, -1);
618
619     if (signfile != NULL) {
620         if (keyfile == NULL)
621             keyfile = signfile;
622         signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
623         if (signer == NULL) {
624             BIO_printf(bio_err, "Error loading signer certificate\n");
625             goto end;
626         }
627         if (sign_certfile != NULL) {
628             if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
629                             "signer certificates"))
630                 goto end;
631         }
632         key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
633                        "signer private key");
634         if (key == NULL)
635             goto end;
636
637         if (!OCSP_request_sign
638             (req, signer, key, NULL, sign_other, sign_flags)) {
639             BIO_printf(bio_err, "Error signing OCSP request\n");
640             goto end;
641         }
642     }
643
644     if (req_text && req != NULL)
645         OCSP_REQUEST_print(out, req, 0);
646
647     if (reqout != NULL) {
648         derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
649         if (derbio == NULL)
650             goto end;
651         i2d_OCSP_REQUEST_bio(derbio, req);
652         BIO_free(derbio);
653     }
654
655     if (rdb != NULL) {
656         make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
657                                rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig);
658         if (cbio != NULL)
659             send_ocsp_response(cbio, resp);
660     } else if (host != NULL) {
661 # ifndef OPENSSL_NO_SOCK
662         resp = process_responder(req, host, path,
663                                  port, use_ssl, headers, req_timeout);
664         if (resp == NULL)
665             goto end;
666 # else
667         BIO_printf(bio_err,
668                    "Error creating connect BIO - sockets not supported.\n");
669         goto end;
670 # endif
671     } else if (respin != NULL) {
672         derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
673         if (derbio == NULL)
674             goto end;
675         resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
676         BIO_free(derbio);
677         if (resp == NULL) {
678             BIO_printf(bio_err, "Error reading OCSP response\n");
679             goto end;
680         }
681     } else {
682         ret = 0;
683         goto end;
684     }
685
686  done_resp:
687
688     if (respout != NULL) {
689         derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
690         if (derbio == NULL)
691             goto end;
692         i2d_OCSP_RESPONSE_bio(derbio, resp);
693         BIO_free(derbio);
694     }
695
696     i = OCSP_response_status(resp);
697     if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
698         BIO_printf(out, "Responder Error: %s (%d)\n",
699                    OCSP_response_status_str(i), i);
700         if (!ignore_err) {
701                 ret = 0;
702                 goto end;
703         }
704     }
705
706     if (resp_text)
707         OCSP_RESPONSE_print(out, resp, 0);
708
709     /* If running as responder don't verify our own response */
710     if (cbio != NULL) {
711         /* If not unlimited, see if we took all we should. */
712         if (accept_count != -1 && --accept_count <= 0) {
713             ret = 0;
714             goto end;
715         }
716         BIO_free_all(cbio);
717         cbio = NULL;
718         OCSP_REQUEST_free(req);
719         req = NULL;
720         OCSP_RESPONSE_free(resp);
721         resp = NULL;
722         goto redo_accept;
723     }
724     if (ridx_filename != NULL) {
725         ret = 0;
726         goto end;
727     }
728
729     if (store == NULL) {
730         store = setup_verify(CAfile, CApath, noCAfile, noCApath);
731         if (!store)
732             goto end;
733     }
734     if (vpmtouched)
735         X509_STORE_set1_param(store, vpm);
736     if (verify_certfile != NULL) {
737         if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
738                         "validator certificate"))
739             goto end;
740     }
741
742     bs = OCSP_response_get1_basic(resp);
743     if (bs == NULL) {
744         BIO_printf(bio_err, "Error parsing response\n");
745         goto end;
746     }
747
748     ret = 0;
749
750     if (!noverify) {
751         if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
752             if (i == -1)
753                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
754             else {
755                 BIO_printf(bio_err, "Nonce Verify error\n");
756                 ret = 1;
757                 goto end;
758             }
759         }
760
761         i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
762         if (i <= 0 && issuers) {
763             i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
764             if (i > 0)
765                 ERR_clear_error();
766         }
767         if (i <= 0) {
768             BIO_printf(bio_err, "Response Verify Failure\n");
769             ERR_print_errors(bio_err);
770             ret = 1;
771         } else {
772             BIO_printf(bio_err, "Response verify OK\n");
773         }
774     }
775
776     print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
777
778  end:
779     ERR_print_errors(bio_err);
780     X509_free(signer);
781     X509_STORE_free(store);
782     X509_VERIFY_PARAM_free(vpm);
783     sk_OPENSSL_STRING_free(rsign_sigopts);
784     EVP_PKEY_free(key);
785     EVP_PKEY_free(rkey);
786     X509_free(cert);
787     sk_X509_pop_free(issuers, X509_free);
788     X509_free(rsigner);
789     sk_X509_pop_free(rca_cert, X509_free);
790     free_index(rdb);
791     BIO_free_all(cbio);
792     BIO_free_all(acbio);
793     BIO_free_all(out);
794     OCSP_REQUEST_free(req);
795     OCSP_RESPONSE_free(resp);
796     OCSP_BASICRESP_free(bs);
797     sk_OPENSSL_STRING_free(reqnames);
798     sk_OCSP_CERTID_free(ids);
799     sk_X509_pop_free(sign_other, X509_free);
800     sk_X509_pop_free(verify_other, X509_free);
801     sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
802     OPENSSL_free(thost);
803     OPENSSL_free(tport);
804     OPENSSL_free(tpath);
805
806     return ret;
807 }
808
809 static void
810 log_message(int level, const char *fmt, ...)
811 {
812     va_list ap;
813
814     va_start(ap, fmt);
815 # ifdef OCSP_DAEMON
816     if (multi) {
817         vsyslog(level, fmt, ap);
818         if (level >= LOG_ERR)
819             ERR_print_errors_cb(print_syslog, &level);
820     }
821 # endif
822     if (!multi) {
823         BIO_printf(bio_err, "%s: ", prog);
824         BIO_vprintf(bio_err, fmt, ap);
825         BIO_printf(bio_err, "\n");
826     }
827     va_end(ap);
828 }
829
830 # ifdef OCSP_DAEMON
831
832 static int print_syslog(const char *str, size_t len, void *levPtr)
833 {
834     int level = *(int *)levPtr;
835     int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
836
837     syslog(level, "%.*s", ilen, str);
838
839     return ilen;
840 }
841
842 static int index_changed(CA_DB *rdb)
843 {
844     struct stat sb;
845
846     if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
847         if (rdb->dbst.st_mtime != sb.st_mtime
848             || rdb->dbst.st_ctime != sb.st_ctime
849             || rdb->dbst.st_ino != sb.st_ino
850             || rdb->dbst.st_dev != sb.st_dev) {
851             syslog(LOG_INFO, "index file changed, reloading");
852             return 1;
853         }
854     }
855     return 0;
856 }
857
858 static void killall(int ret, pid_t *kidpids)
859 {
860     int i;
861
862     for (i = 0; i < multi; ++i)
863         if (kidpids[i] != 0)
864             (void)kill(kidpids[i], SIGTERM);
865     sleep(1);
866     exit(ret);
867 }
868
869 static int termsig = 0;
870
871 static void noteterm (int sig)
872 {
873     termsig = sig;
874 }
875
876 /*
877  * Loop spawning up to `multi` child processes, only child processes return
878  * from this function.  The parent process loops until receiving a termination
879  * signal, kills extant children and exits without returning.
880  */
881 static void spawn_loop(void)
882 {
883     const char *signame;
884     pid_t *kidpids = NULL;
885     int status;
886     int procs = 0;
887     int i;
888
889     openlog(prog, LOG_PID, LOG_DAEMON);
890
891     if (setpgid(0, 0)) {
892         syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
893                strerror(errno));
894         exit(1);
895     }
896     kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
897     for (i = 0; i < multi; ++i)
898         kidpids[i] = 0;
899
900     signal(SIGINT, noteterm);
901     signal(SIGTERM, noteterm);
902
903     while (termsig == 0) {
904         pid_t fpid;
905
906         /*
907          * Wait for a child to replace when we're at the limit.
908          * Slow down if a child exited abnormally or waitpid() < 0
909          */
910         while (termsig == 0 && procs >= multi) {
911             if ((fpid = waitpid(-1, &status, 0)) > 0) {
912                 for (i = 0; i < procs; ++i) {
913                     if (kidpids[i] == fpid) {
914                         kidpids[i] = 0;
915                         --procs;
916                         break;
917                     }
918                 }
919                 if (i >= multi) {
920                     syslog(LOG_ERR, "fatal: internal error: "
921                            "no matching child slot for pid: %ld",
922                            (long) fpid);
923                     killall(1, kidpids);
924                 }
925                 if (status != 0) {
926                     if (WIFEXITED(status))
927                         syslog(LOG_WARNING, "child process: %ld, exit status: %d",
928                                (long)fpid, WEXITSTATUS(status));
929                     else if (WIFSIGNALED(status))
930                         syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
931                                (long)fpid, WTERMSIG(status),
932                                WCOREDUMP(status) ? " (core dumped)" : "");
933                     sleep(1);
934                 }
935                 break;
936             } else if (errno != EINTR) {
937                 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
938                 killall(1, kidpids);
939             }
940         }
941         if (termsig)
942             break;
943
944         switch(fpid = fork()) {
945         case -1:            /* error */
946             /* System critically low on memory, pause and try again later */
947             sleep(30);
948             break;
949         case 0:             /* child */
950             signal(SIGINT, SIG_DFL);
951             signal(SIGTERM, SIG_DFL);
952             if (termsig)
953                 _exit(0);
954             if (RAND_poll() <= 0) {
955                 syslog(LOG_ERR, "fatal: RAND_poll() failed");
956                 _exit(1);
957             }
958             return;
959         default:            /* parent */
960             for (i = 0; i < multi; ++i) {
961                 if (kidpids[i] == 0) {
962                     kidpids[i] = fpid;
963                     procs++;
964                     break;
965                 }
966             }
967             if (i >= multi) {
968                 syslog(LOG_ERR, "fatal: internal error: no free child slots");
969                 killall(1, kidpids);
970             }
971             break;
972         }
973     }
974
975     /* The loop above can only break on termsig */
976     signame = strsignal(termsig);
977     syslog(LOG_INFO, "terminating on signal: %s(%d)",
978            signame ? signame : "", termsig);
979     killall(0, kidpids);
980 }
981 # endif
982
983 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
984                          const EVP_MD *cert_id_md, X509 *issuer,
985                          STACK_OF(OCSP_CERTID) *ids)
986 {
987     OCSP_CERTID *id;
988
989     if (issuer == NULL) {
990         BIO_printf(bio_err, "No issuer certificate specified\n");
991         return 0;
992     }
993     if (*req == NULL)
994         *req = OCSP_REQUEST_new();
995     if (*req == NULL)
996         goto err;
997     id = OCSP_cert_to_id(cert_id_md, cert, issuer);
998     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
999         goto err;
1000     if (!OCSP_request_add0_id(*req, id))
1001         goto err;
1002     return 1;
1003
1004  err:
1005     BIO_printf(bio_err, "Error Creating OCSP request\n");
1006     return 0;
1007 }
1008
1009 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1010                            const EVP_MD *cert_id_md, X509 *issuer,
1011                            STACK_OF(OCSP_CERTID) *ids)
1012 {
1013     OCSP_CERTID *id;
1014     X509_NAME *iname;
1015     ASN1_BIT_STRING *ikey;
1016     ASN1_INTEGER *sno;
1017
1018     if (issuer == NULL) {
1019         BIO_printf(bio_err, "No issuer certificate specified\n");
1020         return 0;
1021     }
1022     if (*req == NULL)
1023         *req = OCSP_REQUEST_new();
1024     if (*req == NULL)
1025         goto err;
1026     iname = X509_get_subject_name(issuer);
1027     ikey = X509_get0_pubkey_bitstr(issuer);
1028     sno = s2i_ASN1_INTEGER(NULL, serial);
1029     if (sno == NULL) {
1030         BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1031         return 0;
1032     }
1033     id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1034     ASN1_INTEGER_free(sno);
1035     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1036         goto err;
1037     if (!OCSP_request_add0_id(*req, id))
1038         goto err;
1039     return 1;
1040
1041  err:
1042     BIO_printf(bio_err, "Error Creating OCSP request\n");
1043     return 0;
1044 }
1045
1046 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1047                               STACK_OF(OPENSSL_STRING) *names,
1048                               STACK_OF(OCSP_CERTID) *ids, long nsec,
1049                               long maxage)
1050 {
1051     OCSP_CERTID *id;
1052     const char *name;
1053     int i, status, reason;
1054     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1055
1056     if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1057         || !sk_OCSP_CERTID_num(ids))
1058         return;
1059
1060     for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1061         id = sk_OCSP_CERTID_value(ids, i);
1062         name = sk_OPENSSL_STRING_value(names, i);
1063         BIO_printf(out, "%s: ", name);
1064
1065         if (!OCSP_resp_find_status(bs, id, &status, &reason,
1066                                    &rev, &thisupd, &nextupd)) {
1067             BIO_puts(out, "ERROR: No Status found.\n");
1068             continue;
1069         }
1070
1071         /*
1072          * Check validity: if invalid write to output BIO so we know which
1073          * response this refers to.
1074          */
1075         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1076             BIO_puts(out, "WARNING: Status times invalid.\n");
1077             ERR_print_errors(out);
1078         }
1079         BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1080
1081         BIO_puts(out, "\tThis Update: ");
1082         ASN1_GENERALIZEDTIME_print(out, thisupd);
1083         BIO_puts(out, "\n");
1084
1085         if (nextupd) {
1086             BIO_puts(out, "\tNext Update: ");
1087             ASN1_GENERALIZEDTIME_print(out, nextupd);
1088             BIO_puts(out, "\n");
1089         }
1090
1091         if (status != V_OCSP_CERTSTATUS_REVOKED)
1092             continue;
1093
1094         if (reason != -1)
1095             BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1096
1097         BIO_puts(out, "\tRevocation Time: ");
1098         ASN1_GENERALIZEDTIME_print(out, rev);
1099         BIO_puts(out, "\n");
1100     }
1101 }
1102
1103 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1104                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1105                               EVP_PKEY *rkey, const EVP_MD *rmd,
1106                               STACK_OF(OPENSSL_STRING) *sigopts,
1107                               STACK_OF(X509) *rother, unsigned long flags,
1108                               int nmin, int ndays, int badsig)
1109 {
1110     ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1111     OCSP_CERTID *cid;
1112     OCSP_BASICRESP *bs = NULL;
1113     int i, id_count;
1114     EVP_MD_CTX *mctx = NULL;
1115     EVP_PKEY_CTX *pkctx = NULL;
1116
1117     id_count = OCSP_request_onereq_count(req);
1118
1119     if (id_count <= 0) {
1120         *resp =
1121             OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1122         goto end;
1123     }
1124
1125     bs = OCSP_BASICRESP_new();
1126     thisupd = X509_gmtime_adj(NULL, 0);
1127     if (ndays != -1)
1128         nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1129
1130     /* Examine each certificate id in the request */
1131     for (i = 0; i < id_count; i++) {
1132         OCSP_ONEREQ *one;
1133         ASN1_INTEGER *serial;
1134         char **inf;
1135         int jj;
1136         int found = 0;
1137         ASN1_OBJECT *cert_id_md_oid;
1138         const EVP_MD *cert_id_md;
1139         one = OCSP_request_onereq_get0(req, i);
1140         cid = OCSP_onereq_get0_id(one);
1141
1142         OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1143
1144         cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1145         if (cert_id_md == NULL) {
1146             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1147                                          NULL);
1148             goto end;
1149         }
1150         for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1151             X509 *ca_cert = sk_X509_value(ca, jj);
1152             OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1153
1154             if (OCSP_id_issuer_cmp(ca_id, cid) == 0)
1155                 found = 1;
1156
1157             OCSP_CERTID_free(ca_id);
1158         }
1159
1160         if (!found) {
1161             OCSP_basic_add1_status(bs, cid,
1162                                    V_OCSP_CERTSTATUS_UNKNOWN,
1163                                    0, NULL, thisupd, nextupd);
1164             continue;
1165         }
1166         OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1167         inf = lookup_serial(db, serial);
1168         if (inf == NULL) {
1169             OCSP_basic_add1_status(bs, cid,
1170                                    V_OCSP_CERTSTATUS_UNKNOWN,
1171                                    0, NULL, thisupd, nextupd);
1172         } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1173             OCSP_basic_add1_status(bs, cid,
1174                                    V_OCSP_CERTSTATUS_GOOD,
1175                                    0, NULL, thisupd, nextupd);
1176         } else if (inf[DB_type][0] == DB_TYPE_REV) {
1177             ASN1_OBJECT *inst = NULL;
1178             ASN1_TIME *revtm = NULL;
1179             ASN1_GENERALIZEDTIME *invtm = NULL;
1180             OCSP_SINGLERESP *single;
1181             int reason = -1;
1182             unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1183             single = OCSP_basic_add1_status(bs, cid,
1184                                             V_OCSP_CERTSTATUS_REVOKED,
1185                                             reason, revtm, thisupd, nextupd);
1186             if (invtm != NULL)
1187                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1188                                              invtm, 0, 0);
1189             else if (inst != NULL)
1190                 OCSP_SINGLERESP_add1_ext_i2d(single,
1191                                              NID_hold_instruction_code, inst,
1192                                              0, 0);
1193             ASN1_OBJECT_free(inst);
1194             ASN1_TIME_free(revtm);
1195             ASN1_GENERALIZEDTIME_free(invtm);
1196         }
1197     }
1198
1199     OCSP_copy_nonce(bs, req);
1200
1201     mctx = EVP_MD_CTX_new();
1202     if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1203         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1204         goto end;
1205     }
1206     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1207         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1208
1209         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1210             BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1211             ERR_print_errors(bio_err);
1212             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1213                                          NULL);
1214             goto end;
1215         }
1216     }
1217     OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags);
1218
1219     if (badsig) {
1220         const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1221         corrupt_signature(sig);
1222     }
1223
1224     *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1225
1226  end:
1227     EVP_MD_CTX_free(mctx);
1228     ASN1_TIME_free(thisupd);
1229     ASN1_TIME_free(nextupd);
1230     OCSP_BASICRESP_free(bs);
1231 }
1232
1233 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1234 {
1235     int i;
1236     BIGNUM *bn = NULL;
1237     char *itmp, *row[DB_NUMBER], **rrow;
1238     for (i = 0; i < DB_NUMBER; i++)
1239         row[i] = NULL;
1240     bn = ASN1_INTEGER_to_BN(ser, NULL);
1241     OPENSSL_assert(bn);         /* FIXME: should report an error at this
1242                                  * point and abort */
1243     if (BN_is_zero(bn))
1244         itmp = OPENSSL_strdup("00");
1245     else
1246         itmp = BN_bn2hex(bn);
1247     row[DB_serial] = itmp;
1248     BN_free(bn);
1249     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1250     OPENSSL_free(itmp);
1251     return rrow;
1252 }
1253
1254 /* Quick and dirty OCSP server: read in and parse input request */
1255
1256 static BIO *init_responder(const char *port)
1257 {
1258 # ifdef OPENSSL_NO_SOCK
1259     BIO_printf(bio_err,
1260                "Error setting up accept BIO - sockets not supported.\n");
1261     return NULL;
1262 # else
1263     BIO *acbio = NULL, *bufbio = NULL;
1264
1265     bufbio = BIO_new(BIO_f_buffer());
1266     if (bufbio == NULL)
1267         goto err;
1268     acbio = BIO_new(BIO_s_accept());
1269     if (acbio == NULL
1270         || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1271         || BIO_set_accept_port(acbio, port) < 0) {
1272         log_message(LOG_ERR, "Error setting up accept BIO");
1273         goto err;
1274     }
1275
1276     BIO_set_accept_bios(acbio, bufbio);
1277     bufbio = NULL;
1278     if (BIO_do_accept(acbio) <= 0) {
1279         log_message(LOG_ERR, "Error starting accept");
1280         goto err;
1281     }
1282
1283     return acbio;
1284
1285  err:
1286     BIO_free_all(acbio);
1287     BIO_free(bufbio);
1288     return NULL;
1289 # endif
1290 }
1291
1292 # ifndef OPENSSL_NO_SOCK
1293 /*
1294  * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1295  */
1296 static int urldecode(char *p)
1297 {
1298     unsigned char *out = (unsigned char *)p;
1299     unsigned char *save = out;
1300
1301     for (; *p; p++) {
1302         if (*p != '%')
1303             *out++ = *p;
1304         else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1305             /* Don't check, can't fail because of ixdigit() call. */
1306             *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1307                    | OPENSSL_hexchar2int(p[2]);
1308             p += 2;
1309         }
1310         else
1311             return -1;
1312     }
1313     *out = '\0';
1314     return (int)(out - save);
1315 }
1316 # endif
1317
1318 # ifdef OCSP_DAEMON
1319 static void sock_timeout(int signum)
1320 {
1321     if (acfd != (int)INVALID_SOCKET)
1322         (void)shutdown(acfd, SHUT_RD);
1323 }
1324 # endif
1325
1326 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1327                         int timeout)
1328 {
1329 # ifdef OPENSSL_NO_SOCK
1330     return 0;
1331 # else
1332     int len;
1333     OCSP_REQUEST *req = NULL;
1334     char inbuf[2048], reqbuf[2048];
1335     char *p, *q;
1336     BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1337     const char *client;
1338
1339     *preq = NULL;
1340
1341     /* Connection loss before accept() is routine, ignore silently */
1342     if (BIO_do_accept(acbio) <= 0)
1343         return 0;
1344
1345     cbio = BIO_pop(acbio);
1346     *pcbio = cbio;
1347     client = BIO_get_peer_name(cbio);
1348
1349 #  ifdef OCSP_DAEMON
1350     if (timeout > 0) {
1351         (void) BIO_get_fd(cbio, &acfd);
1352         alarm(timeout);
1353     }
1354 #  endif
1355
1356     /* Read the request line. */
1357     len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1358     if (len <= 0)
1359         goto out;
1360
1361     if (strncmp(reqbuf, "GET ", 4) == 0) {
1362         /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1363         for (p = reqbuf + 4; *p == ' '; ++p)
1364             continue;
1365         if (*p != '/') {
1366             log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1367             goto out;
1368         }
1369         p++;
1370
1371         /* Splice off the HTTP version identifier. */
1372         for (q = p; *q; q++)
1373             if (*q == ' ')
1374                 break;
1375         if (strncmp(q, " HTTP/1.", 8) != 0) {
1376             log_message(LOG_INFO,
1377                         "Invalid request -- bad HTTP version: %s", client);
1378             goto out;
1379         }
1380         *q = '\0';
1381
1382         /*
1383          * Skip "GET / HTTP..." requests often used by load-balancers
1384          */
1385         if (p[1] == '\0')
1386             goto out;
1387
1388         len = urldecode(p);
1389         if (len <= 0) {
1390             log_message(LOG_INFO,
1391                         "Invalid request -- bad URL encoding: %s", client);
1392             goto out;
1393         }
1394         if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1395             || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1396             log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1397             goto out;
1398         }
1399         BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1400         getbio = BIO_push(b64, getbio);
1401     } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1402         log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1403         goto out;
1404     }
1405
1406     /* Read and skip past the headers. */
1407     for (;;) {
1408         len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1409         if (len <= 0)
1410             goto out;
1411         if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1412             break;
1413     }
1414
1415 #  ifdef OCSP_DAEMON
1416     /* Clear alarm before we close the client socket */
1417     alarm(0);
1418     timeout = 0;
1419 #  endif
1420
1421     /* Try to read OCSP request */
1422     if (getbio != NULL) {
1423         req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1424         BIO_free_all(getbio);
1425     } else {
1426         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1427     }
1428
1429     if (req == NULL)
1430         log_message(LOG_ERR, "Error parsing OCSP request");
1431
1432     *preq = req;
1433
1434 out:
1435 #  ifdef OCSP_DAEMON
1436     if (timeout > 0)
1437         alarm(0);
1438     acfd = (int)INVALID_SOCKET;
1439 #  endif
1440     return 1;
1441 # endif
1442 }
1443
1444 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1445 {
1446     char http_resp[] =
1447         "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1448         "Content-Length: %d\r\n\r\n";
1449     if (cbio == NULL)
1450         return 0;
1451     BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1452     i2d_OCSP_RESPONSE_bio(cbio, resp);
1453     (void)BIO_flush(cbio);
1454     return 1;
1455 }
1456
1457 # ifndef OPENSSL_NO_SOCK
1458 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1459                                       const char *path,
1460                                       const STACK_OF(CONF_VALUE) *headers,
1461                                       OCSP_REQUEST *req, int req_timeout)
1462 {
1463     int fd;
1464     int rv;
1465     int i;
1466     int add_host = 1;
1467     OCSP_REQ_CTX *ctx = NULL;
1468     OCSP_RESPONSE *rsp = NULL;
1469     fd_set confds;
1470     struct timeval tv;
1471
1472     if (req_timeout != -1)
1473         BIO_set_nbio(cbio, 1);
1474
1475     rv = BIO_do_connect(cbio);
1476
1477     if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1478         BIO_puts(bio_err, "Error connecting BIO\n");
1479         return NULL;
1480     }
1481
1482     if (BIO_get_fd(cbio, &fd) < 0) {
1483         BIO_puts(bio_err, "Can't get connection fd\n");
1484         goto err;
1485     }
1486
1487     if (req_timeout != -1 && rv <= 0) {
1488         FD_ZERO(&confds);
1489         openssl_fdset(fd, &confds);
1490         tv.tv_usec = 0;
1491         tv.tv_sec = req_timeout;
1492         rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1493         if (rv == 0) {
1494             BIO_puts(bio_err, "Timeout on connect\n");
1495             return NULL;
1496         }
1497     }
1498
1499     ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1500     if (ctx == NULL)
1501         return NULL;
1502
1503     for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1504         CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1505         if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1506             add_host = 0;
1507         if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1508             goto err;
1509     }
1510
1511     if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1512         goto err;
1513
1514     if (!OCSP_REQ_CTX_set1_req(ctx, req))
1515         goto err;
1516
1517     for (;;) {
1518         rv = OCSP_sendreq_nbio(&rsp, ctx);
1519         if (rv != -1)
1520             break;
1521         if (req_timeout == -1)
1522             continue;
1523         FD_ZERO(&confds);
1524         openssl_fdset(fd, &confds);
1525         tv.tv_usec = 0;
1526         tv.tv_sec = req_timeout;
1527         if (BIO_should_read(cbio)) {
1528             rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1529         } else if (BIO_should_write(cbio)) {
1530             rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1531         } else {
1532             BIO_puts(bio_err, "Unexpected retry condition\n");
1533             goto err;
1534         }
1535         if (rv == 0) {
1536             BIO_puts(bio_err, "Timeout on request\n");
1537             break;
1538         }
1539         if (rv == -1) {
1540             BIO_puts(bio_err, "Select error\n");
1541             break;
1542         }
1543
1544     }
1545  err:
1546     OCSP_REQ_CTX_free(ctx);
1547
1548     return rsp;
1549 }
1550
1551 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1552                                  const char *host, const char *path,
1553                                  const char *port, int use_ssl,
1554                                  STACK_OF(CONF_VALUE) *headers,
1555                                  int req_timeout)
1556 {
1557     BIO *cbio = NULL;
1558     SSL_CTX *ctx = NULL;
1559     OCSP_RESPONSE *resp = NULL;
1560
1561     cbio = BIO_new_connect(host);
1562     if (cbio == NULL) {
1563         BIO_printf(bio_err, "Error creating connect BIO\n");
1564         goto end;
1565     }
1566     if (port != NULL)
1567         BIO_set_conn_port(cbio, port);
1568     if (use_ssl == 1) {
1569         BIO *sbio;
1570         ctx = SSL_CTX_new(TLS_client_method());
1571         if (ctx == NULL) {
1572             BIO_printf(bio_err, "Error creating SSL context.\n");
1573             goto end;
1574         }
1575         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1576         sbio = BIO_new_ssl(ctx, 1);
1577         cbio = BIO_push(sbio, cbio);
1578     }
1579
1580     resp = query_responder(cbio, host, path, headers, req, req_timeout);
1581     if (resp == NULL)
1582         BIO_printf(bio_err, "Error querying OCSP responder\n");
1583  end:
1584     BIO_free_all(cbio);
1585     SSL_CTX_free(ctx);
1586     return resp;
1587 }
1588 # endif
1589
1590 #endif