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