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