Avoid negative array index in BIO_debug_callback()
[openssl.git] / apps / ocsp.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
3  * 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 #ifndef OPENSSL_NO_OCSP
59
60 # ifdef OPENSSL_SYS_VMS
61 #  define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
62                                  * on OpenVMS */
63 # endif
64
65 # define USE_SOCKETS
66
67 # include <stdio.h>
68 # include <stdlib.h>
69 # include <string.h>
70 # include <time.h>
71 # include <ctype.h>
72 # include "apps.h"              /* needs to be included before the openssl
73                                  * headers! */
74 # include <openssl/e_os2.h>
75 # include <openssl/crypto.h>
76 # include <openssl/err.h>
77 # include <openssl/ssl.h>
78 # include <openssl/evp.h>
79 # include <openssl/bn.h>
80 # include <openssl/x509v3.h>
81
82 # if defined(NETWARE_CLIB)
83 #  ifdef NETWARE_BSDSOCK
84 #   include <sys/socket.h>
85 #   include <sys/bsdskt.h>
86 #  else
87 #   include <novsock2.h>
88 #  endif
89 # elif defined(NETWARE_LIBC)
90 #  ifdef NETWARE_BSDSOCK
91 #   include <sys/select.h>
92 #  else
93 #   include <novsock2.h>
94 #  endif
95 # endif
96
97 /* Maximum leeway in validity period: default 5 minutes */
98 # define MAX_VALIDITY_PERIOD    (5 * 60)
99
100 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
101                          const EVP_MD *cert_id_md, X509 *issuer,
102                          STACK_OF(OCSP_CERTID) *ids);
103 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
104                            const EVP_MD *cert_id_md, X509 *issuer,
105                            STACK_OF(OCSP_CERTID) *ids);
106 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
107                               STACK_OF(OPENSSL_STRING) *names,
108                               STACK_OF(OCSP_CERTID) *ids, long nsec,
109                               long maxage);
110 static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req,
111                               CA_DB *db, X509 *ca, X509 *rcert,
112                               EVP_PKEY *rkey, const EVP_MD *md,
113                               STACK_OF(X509) *rother, unsigned long flags,
114                               int nmin, int ndays, int badsig);
115
116 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
117 static BIO *init_responder(const char *port);
118 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio);
119 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
120 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
121                                       const char *path,
122                                       const STACK_OF(CONF_VALUE) *headers,
123                                       OCSP_REQUEST *req, int req_timeout);
124
125 typedef enum OPTION_choice {
126     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
127     OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
128     OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
129     OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
130     OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
131     OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
132     OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
133     OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
134     OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH,
135     OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
136     OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
137     OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
138     OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_HEADER,
139     OPT_V_ENUM,
140     OPT_MD
141 } OPTION_CHOICE;
142
143 OPTIONS ocsp_options[] = {
144     {"help", OPT_HELP, '-', "Display this summary"},
145     {"out", OPT_OUTFILE, '>', "Output filename"},
146     {"timeout", OPT_TIMEOUT, 'p',
147      "Connection timeout (in seconds) to the OCSP responder"},
148     {"url", OPT_URL, 's', "Responder URL"},
149     {"host", OPT_HOST, 's', "host:prot top to connect to"},
150     {"port", OPT_PORT, 'p', "Port to run responder on"},
151     {"ignore_err", OPT_IGNORE_ERR, '-'},
152     {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
153     {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
154     {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
155     {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
156      "Don't include any certificates in response"},
157     {"resp_key_id", OPT_RESP_KEY_ID, '-',
158      "Identify reponse by signing certificate key ID"},
159     {"no_certs", OPT_NO_CERTS, '-',
160      "Don't include any certificates in signed request"},
161     {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
162      "Don't check signature on response"},
163     {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
164      "Don't check signing certificate"},
165     {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
166     {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
167      "Don't do additional checks on signing certificate"},
168     {"no_explicit", OPT_NO_EXPLICIT, '-'},
169     {"trust_other", OPT_TRUST_OTHER, '-',
170      "Don't verify additional certificates"},
171     {"no_intern", OPT_NO_INTERN, '-',
172      "Don't search certificates contained in response for signer"},
173     {"badsig", OPT_BADSIG, '-'},
174     {"text", OPT_TEXT, '-', "Print text form of request and response"},
175     {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
176     {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
177     {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
178     {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
179     {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
180     {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
181     {"sign_other", OPT_SIGN_OTHER, '<',
182      "Additional certificates to include in signed request"},
183     {"verify_other", OPT_VERIFY_OTHER, '<',
184      "Additional certificates to search for signer"},
185     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
186     {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
187     {"no-CAfile", OPT_NOCAFILE, '-',
188      "Do not load the default certificates file"},
189     {"no-CApath", OPT_NOCAPATH, '-',
190      "Do not load certificates from the default certificates directory"},
191     {"validity_period", OPT_VALIDITY_PERIOD, 'u',
192      "Maximum validity discrepancy in seconds"},
193     {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
194     {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
195     {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
196     {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
197     {"path", OPT_PATH, 's', "Path to use in OCSP request"},
198     {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
199     {"cert", OPT_CERT, '<', "Certificate to check"},
200     {"serial", OPT_SERIAL, 's', "Nerial number to check"},
201     {"index", OPT_INDEX, '<', "Certificate status index file"},
202     {"CA", OPT_CA, '<', "CA certificate"},
203     {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
204     {"nrequest", OPT_REQUEST, 'p',
205      "Number of requests to accept (default unlimited)"},
206     {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
207     {"rsigner", OPT_RSIGNER, '<',
208      "Sesponder certificate to sign responses with"},
209     {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
210     {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
211     {"rmd", OPT_RMD, 's'},
212     {"header", OPT_HEADER, 's', "key=value header to add"},
213     {"", OPT_MD, '-', "Any supported digest"},
214     OPT_V_OPTIONS,
215     {NULL}
216 };
217
218 int ocsp_main(int argc, char **argv)
219 {
220     BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
221     const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
222     CA_DB *rdb = NULL;
223     EVP_PKEY *key = NULL, *rkey = NULL;
224     OCSP_BASICRESP *bs = NULL;
225     OCSP_REQUEST *req = NULL;
226     OCSP_RESPONSE *resp = NULL;
227     STACK_OF(CONF_VALUE) *headers = NULL;
228     STACK_OF(OCSP_CERTID) *ids = NULL;
229     STACK_OF(OPENSSL_STRING) *reqnames = NULL;
230     STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
231     STACK_OF(X509) *issuers = NULL;
232     X509 *issuer = NULL, *cert = NULL, *rca_cert = NULL;
233     X509 *signer = NULL, *rsigner = NULL;
234     X509_STORE *store = NULL;
235     X509_VERIFY_PARAM *vpm = NULL;
236     char *CAfile = NULL, *CApath = NULL, *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, req_timeout = -1, ret = 1;
248     long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
249     unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
250     OPTION_CHOICE o;
251     char *prog;
252
253     reqnames = sk_OPENSSL_STRING_new_null();
254     if (!reqnames)
255         goto end;
256     ids = sk_OCSP_CERTID_new_null();
257     if (!ids)
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             req_timeout = atoi(opt_arg());
279             break;
280         case OPT_URL:
281             OPENSSL_free(thost);
282             OPENSSL_free(tport);
283             OPENSSL_free(tpath);
284             thost = tport = tpath = NULL;
285             if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
286                 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
287                 goto end;
288             }
289             thost = host;
290             tport = port;
291             tpath = path;
292             break;
293         case OPT_HOST:
294             host = opt_arg();
295             break;
296         case OPT_PORT:
297             port = opt_arg();
298             break;
299         case OPT_IGNORE_ERR:
300             ignore_err = 1;
301             break;
302         case OPT_NOVERIFY:
303             noverify = 1;
304             break;
305         case OPT_NONCE:
306             add_nonce = 2;
307             break;
308         case OPT_NO_NONCE:
309             add_nonce = 0;
310             break;
311         case OPT_RESP_NO_CERTS:
312             rflags |= OCSP_NOCERTS;
313             break;
314         case OPT_RESP_KEY_ID:
315             rflags |= OCSP_RESPID_KEY;
316             break;
317         case OPT_NO_CERTS:
318             sign_flags |= OCSP_NOCERTS;
319             break;
320         case OPT_NO_SIGNATURE_VERIFY:
321             verify_flags |= OCSP_NOSIGS;
322             break;
323         case OPT_NO_CERT_VERIFY:
324             verify_flags |= OCSP_NOVERIFY;
325             break;
326         case OPT_NO_CHAIN:
327             verify_flags |= OCSP_NOCHAIN;
328             break;
329         case OPT_NO_CERT_CHECKS:
330             verify_flags |= OCSP_NOCHECKS;
331             break;
332         case OPT_NO_EXPLICIT:
333             verify_flags |= OCSP_NOEXPLICIT;
334             break;
335         case OPT_TRUST_OTHER:
336             verify_flags |= OCSP_TRUSTOTHER;
337             break;
338         case OPT_NO_INTERN:
339             verify_flags |= OCSP_NOINTERN;
340             break;
341         case OPT_BADSIG:
342             badsig = 1;
343             break;
344         case OPT_TEXT:
345             req_text = resp_text = 1;
346             break;
347         case OPT_REQ_TEXT:
348             req_text = 1;
349             break;
350         case OPT_RESP_TEXT:
351             resp_text = 1;
352             break;
353         case OPT_REQIN:
354             reqin = opt_arg();
355             break;
356         case OPT_RESPIN:
357             respin = opt_arg();
358             break;
359         case OPT_SIGNER:
360             signfile = opt_arg();
361             break;
362         case OPT_VAFILE:
363             verify_certfile = opt_arg();
364             verify_flags |= OCSP_TRUSTOTHER;
365             break;
366         case OPT_SIGN_OTHER:
367             sign_certfile = opt_arg();
368             break;
369         case OPT_VERIFY_OTHER:
370             verify_certfile = opt_arg();
371             break;
372         case OPT_CAFILE:
373             CAfile = opt_arg();
374             break;
375         case OPT_CAPATH:
376             CApath = opt_arg();
377             break;
378         case OPT_NOCAFILE:
379             noCAfile = 1;
380             break;
381         case OPT_NOCAPATH:
382             noCApath = 1;
383             break;
384         case OPT_V_CASES:
385             if (!opt_verify(o, vpm))
386                 goto end;
387             vpmtouched++;
388             break;
389         case OPT_VALIDITY_PERIOD:
390             opt_long(opt_arg(), &nsec);
391             break;
392         case OPT_STATUS_AGE:
393             opt_long(opt_arg(), &maxage);
394             break;
395         case OPT_SIGNKEY:
396             keyfile = opt_arg();
397             break;
398         case OPT_REQOUT:
399             reqout = opt_arg();
400             break;
401         case OPT_RESPOUT:
402             respout = opt_arg();
403             break;
404         case OPT_PATH:
405             path = opt_arg();
406             break;
407         case OPT_ISSUER:
408             issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
409             if (issuer == NULL)
410                 goto end;
411             if (issuers == NULL) {
412                 if ((issuers = sk_X509_new_null()) == NULL)
413                     goto end;
414             }
415             sk_X509_push(issuers, issuer);
416             break;
417         case OPT_CERT:
418             X509_free(cert);
419             cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
420             if (cert == NULL)
421                 goto end;
422             if (cert_id_md == NULL)
423                 cert_id_md = EVP_sha1();
424             if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
425                 goto end;
426             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
427                 goto end;
428             break;
429         case OPT_SERIAL:
430             if (cert_id_md == NULL)
431                 cert_id_md = EVP_sha1();
432             if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
433                 goto end;
434             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
435                 goto end;
436             break;
437         case OPT_INDEX:
438             ridx_filename = opt_arg();
439             break;
440         case OPT_CA:
441             rca_filename = opt_arg();
442             break;
443         case OPT_NMIN:
444             opt_int(opt_arg(), &nmin);
445             if (ndays == -1)
446                 ndays = 0;
447             break;
448         case OPT_REQUEST:
449             opt_int(opt_arg(), &accept_count);
450             break;
451         case OPT_NDAYS:
452             ndays = atoi(opt_arg());
453             break;
454         case OPT_RSIGNER:
455             rsignfile = opt_arg();
456             break;
457         case OPT_RKEY:
458             rkeyfile = opt_arg();
459             break;
460         case OPT_ROTHER:
461             rcertfile = opt_arg();
462             break;
463         case OPT_RMD:
464             if (!opt_md(opt_arg(), &rsign_md))
465                 goto end;
466             break;
467         case OPT_HEADER:
468             header = opt_arg();
469             value = strchr(header, '=');
470             if (value == NULL) {
471                 BIO_printf(bio_err, "Missing = in header key=value\n");
472                 goto opthelp;
473             }
474             *value++ = '\0';
475             if (!X509V3_add_value(header, value, &headers))
476                 goto end;
477             break;
478         case OPT_MD:
479             if (cert_id_md != NULL) {
480                 BIO_printf(bio_err,
481                            "%s: Digest must be before -cert or -serial\n",
482                            prog);
483                 goto opthelp;
484             }
485             if (!opt_md(opt_unknown(), &cert_id_md))
486                 goto opthelp;
487             break;
488         }
489     }
490     argc = opt_num_rest();
491     if (argc != 0)
492         goto opthelp;
493
494     /* Have we anything to do? */
495     if (!req && !reqin && !respin && !(port && ridx_filename))
496         goto opthelp;
497
498     out = bio_open_default(outfile, 'w', FORMAT_TEXT);
499     if (out == NULL)
500         goto end;
501
502     if (!req && (add_nonce != 2))
503         add_nonce = 0;
504
505     if (!req && reqin) {
506         derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
507         if (derbio == NULL)
508             goto end;
509         req = d2i_OCSP_REQUEST_bio(derbio, NULL);
510         BIO_free(derbio);
511         if (!req) {
512             BIO_printf(bio_err, "Error reading OCSP request\n");
513             goto end;
514         }
515     }
516
517     if (!req && port) {
518         acbio = init_responder(port);
519         if (!acbio)
520             goto end;
521     }
522
523     if (rsignfile) {
524         if (!rkeyfile)
525             rkeyfile = rsignfile;
526         rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
527         if (!rsigner) {
528             BIO_printf(bio_err, "Error loading responder certificate\n");
529             goto end;
530         }
531         rca_cert = load_cert(rca_filename, FORMAT_PEM, "CA certificate");
532         if (rcertfile) {
533             if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
534                             "responder other certificates"))
535                 goto end;
536         }
537         rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
538                         "responder private key");
539         if (!rkey)
540             goto end;
541     }
542     if (acbio)
543         BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
544
545  redo_accept:
546
547     if (acbio) {
548         if (!do_responder(&req, &cbio, acbio))
549             goto end;
550         if (!req) {
551             resp =
552                 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
553                                      NULL);
554             send_ocsp_response(cbio, resp);
555             goto done_resp;
556         }
557     }
558
559     if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
560         BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
561         goto end;
562     }
563
564     if (req && add_nonce)
565         OCSP_request_add1_nonce(req, NULL, -1);
566
567     if (signfile) {
568         if (!keyfile)
569             keyfile = signfile;
570         signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
571         if (!signer) {
572             BIO_printf(bio_err, "Error loading signer certificate\n");
573             goto end;
574         }
575         if (sign_certfile) {
576             if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
577                             "signer certificates"))
578                 goto end;
579         }
580         key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
581                        "signer private key");
582         if (!key)
583             goto end;
584
585         if (!OCSP_request_sign
586             (req, signer, key, NULL, sign_other, sign_flags)) {
587             BIO_printf(bio_err, "Error signing OCSP request\n");
588             goto end;
589         }
590     }
591
592     if (req_text && req)
593         OCSP_REQUEST_print(out, req, 0);
594
595     if (reqout) {
596         derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
597         if (derbio == NULL)
598             goto end;
599         i2d_OCSP_REQUEST_bio(derbio, req);
600         BIO_free(derbio);
601     }
602
603     if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
604         BIO_printf(bio_err,
605                    "Need a responder certificate, key and CA for this operation!\n");
606         goto end;
607     }
608
609     if (ridx_filename && !rdb) {
610         rdb = load_index(ridx_filename, NULL);
611         if (!rdb)
612             goto end;
613         if (!index_index(rdb))
614             goto end;
615     }
616
617     if (rdb) {
618         make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey,
619                                rsign_md, rother, rflags, nmin, ndays, badsig);
620         if (cbio)
621             send_ocsp_response(cbio, resp);
622     } else if (host) {
623 # ifndef OPENSSL_NO_SOCK
624         resp = process_responder(req, host, path,
625                                  port, use_ssl, headers, req_timeout);
626         if (!resp)
627             goto end;
628 # else
629         BIO_printf(bio_err,
630                    "Error creating connect BIO - sockets not supported.\n");
631         goto end;
632 # endif
633     } else if (respin) {
634         derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
635         if (derbio == NULL)
636             goto end;
637         resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
638         BIO_free(derbio);
639         if (!resp) {
640             BIO_printf(bio_err, "Error reading OCSP response\n");
641             goto end;
642         }
643     } else {
644         ret = 0;
645         goto end;
646     }
647
648  done_resp:
649
650     if (respout) {
651         derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
652         if (derbio == NULL)
653             goto end;
654         i2d_OCSP_RESPONSE_bio(derbio, resp);
655         BIO_free(derbio);
656     }
657
658     i = OCSP_response_status(resp);
659     if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
660         BIO_printf(out, "Responder Error: %s (%d)\n",
661                    OCSP_response_status_str(i), i);
662         if (ignore_err)
663             goto redo_accept;
664         ret = 0;
665         goto end;
666     }
667
668     if (resp_text)
669         OCSP_RESPONSE_print(out, resp, 0);
670
671     /* If running as responder don't verify our own response */
672     if (cbio) {
673         /* If not unlimited, see if we took all we should. */
674         if (accept_count != -1 && --accept_count <= 0) {
675             ret = 0;
676             goto end;
677         }
678         BIO_free_all(cbio);
679         cbio = NULL;
680         OCSP_REQUEST_free(req);
681         req = NULL;
682         OCSP_RESPONSE_free(resp);
683         resp = NULL;
684         goto redo_accept;
685     }
686     if (ridx_filename) {
687         ret = 0;
688         goto end;
689     }
690
691     if (!store) {
692         store = setup_verify(CAfile, CApath, noCAfile, noCApath);
693         if (!store)
694             goto end;
695     }
696     if (vpmtouched)
697         X509_STORE_set1_param(store, vpm);
698     if (verify_certfile) {
699         if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
700                         "validator certificate"))
701             goto end;
702     }
703
704     bs = OCSP_response_get1_basic(resp);
705     if (!bs) {
706         BIO_printf(bio_err, "Error parsing response\n");
707         goto end;
708     }
709
710     ret = 0;
711
712     if (!noverify) {
713         if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
714             if (i == -1)
715                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
716             else {
717                 BIO_printf(bio_err, "Nonce Verify error\n");
718                 ret = 1;
719                 goto end;
720             }
721         }
722
723         i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
724         if (i <= 0 && issuers) {
725             i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
726             if (i > 0)
727                 ERR_clear_error();
728         }
729         if (i <= 0) {
730             BIO_printf(bio_err, "Response Verify Failure\n");
731             ERR_print_errors(bio_err);
732             ret = 1;
733         } else
734             BIO_printf(bio_err, "Response verify OK\n");
735
736     }
737
738     print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
739
740  end:
741     ERR_print_errors(bio_err);
742     X509_free(signer);
743     X509_STORE_free(store);
744     X509_VERIFY_PARAM_free(vpm);
745     EVP_PKEY_free(key);
746     EVP_PKEY_free(rkey);
747     X509_free(cert);
748     sk_X509_pop_free(issuers, X509_free);
749     X509_free(rsigner);
750     X509_free(rca_cert);
751     free_index(rdb);
752     BIO_free_all(cbio);
753     BIO_free_all(acbio);
754     BIO_free(out);
755     OCSP_REQUEST_free(req);
756     OCSP_RESPONSE_free(resp);
757     OCSP_BASICRESP_free(bs);
758     sk_OPENSSL_STRING_free(reqnames);
759     sk_OCSP_CERTID_free(ids);
760     sk_X509_pop_free(sign_other, X509_free);
761     sk_X509_pop_free(verify_other, X509_free);
762     sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
763     OPENSSL_free(thost);
764     OPENSSL_free(tport);
765     OPENSSL_free(tpath);
766
767     return (ret);
768 }
769
770 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
771                          const EVP_MD *cert_id_md, X509 *issuer,
772                          STACK_OF(OCSP_CERTID) *ids)
773 {
774     OCSP_CERTID *id;
775     if (!issuer) {
776         BIO_printf(bio_err, "No issuer certificate specified\n");
777         return 0;
778     }
779     if (*req == NULL)
780         *req = OCSP_REQUEST_new();
781     if (*req == NULL)
782         goto err;
783     id = OCSP_cert_to_id(cert_id_md, cert, issuer);
784     if (!id || !sk_OCSP_CERTID_push(ids, id))
785         goto err;
786     if (!OCSP_request_add0_id(*req, id))
787         goto err;
788     return 1;
789
790  err:
791     BIO_printf(bio_err, "Error Creating OCSP request\n");
792     return 0;
793 }
794
795 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
796                            const EVP_MD *cert_id_md, X509 *issuer,
797                            STACK_OF(OCSP_CERTID) *ids)
798 {
799     OCSP_CERTID *id;
800     X509_NAME *iname;
801     ASN1_BIT_STRING *ikey;
802     ASN1_INTEGER *sno;
803     if (!issuer) {
804         BIO_printf(bio_err, "No issuer certificate specified\n");
805         return 0;
806     }
807     if (*req == NULL)
808         *req = OCSP_REQUEST_new();
809     if (*req == NULL)
810         goto err;
811     iname = X509_get_subject_name(issuer);
812     ikey = X509_get0_pubkey_bitstr(issuer);
813     sno = s2i_ASN1_INTEGER(NULL, serial);
814     if (!sno) {
815         BIO_printf(bio_err, "Error converting serial number %s\n", serial);
816         return 0;
817     }
818     id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
819     ASN1_INTEGER_free(sno);
820     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
821         goto err;
822     if (!OCSP_request_add0_id(*req, id))
823         goto err;
824     return 1;
825
826  err:
827     BIO_printf(bio_err, "Error Creating OCSP request\n");
828     return 0;
829 }
830
831 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
832                               STACK_OF(OPENSSL_STRING) *names,
833                               STACK_OF(OCSP_CERTID) *ids, long nsec,
834                               long maxage)
835 {
836     OCSP_CERTID *id;
837     char *name;
838     int i, status, reason;
839     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
840
841     if (!bs || !req || !sk_OPENSSL_STRING_num(names)
842         || !sk_OCSP_CERTID_num(ids))
843         return;
844
845     for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
846         id = sk_OCSP_CERTID_value(ids, i);
847         name = sk_OPENSSL_STRING_value(names, i);
848         BIO_printf(out, "%s: ", name);
849
850         if (!OCSP_resp_find_status(bs, id, &status, &reason,
851                                    &rev, &thisupd, &nextupd)) {
852             BIO_puts(out, "ERROR: No Status found.\n");
853             continue;
854         }
855
856         /*
857          * Check validity: if invalid write to output BIO so we know which
858          * response this refers to.
859          */
860         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
861             BIO_puts(out, "WARNING: Status times invalid.\n");
862             ERR_print_errors(out);
863         }
864         BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
865
866         BIO_puts(out, "\tThis Update: ");
867         ASN1_GENERALIZEDTIME_print(out, thisupd);
868         BIO_puts(out, "\n");
869
870         if (nextupd) {
871             BIO_puts(out, "\tNext Update: ");
872             ASN1_GENERALIZEDTIME_print(out, nextupd);
873             BIO_puts(out, "\n");
874         }
875
876         if (status != V_OCSP_CERTSTATUS_REVOKED)
877             continue;
878
879         if (reason != -1)
880             BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
881
882         BIO_puts(out, "\tRevocation Time: ");
883         ASN1_GENERALIZEDTIME_print(out, rev);
884         BIO_puts(out, "\n");
885     }
886 }
887
888 static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req,
889                               CA_DB *db, X509 *ca, X509 *rcert,
890                               EVP_PKEY *rkey, const EVP_MD *rmd,
891                               STACK_OF(X509) *rother, unsigned long flags,
892                               int nmin, int ndays, int badsig)
893 {
894     ASN1_TIME *thisupd = NULL, *nextupd = NULL;
895     OCSP_CERTID *cid, *ca_id = NULL;
896     OCSP_BASICRESP *bs = NULL;
897     int i, id_count;
898
899     id_count = OCSP_request_onereq_count(req);
900
901     if (id_count <= 0) {
902         *resp =
903             OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
904         goto end;
905     }
906
907     bs = OCSP_BASICRESP_new();
908     thisupd = X509_gmtime_adj(NULL, 0);
909     if (ndays != -1)
910         nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
911
912     /* Examine each certificate id in the request */
913     for (i = 0; i < id_count; i++) {
914         OCSP_ONEREQ *one;
915         ASN1_INTEGER *serial;
916         char **inf;
917         ASN1_OBJECT *cert_id_md_oid;
918         const EVP_MD *cert_id_md;
919         one = OCSP_request_onereq_get0(req, i);
920         cid = OCSP_onereq_get0_id(one);
921
922         OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
923
924         cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
925         if (!cert_id_md) {
926             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
927                                          NULL);
928             goto end;
929         }
930         OCSP_CERTID_free(ca_id);
931         ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca);
932
933         /* Is this request about our CA? */
934         if (OCSP_id_issuer_cmp(ca_id, cid)) {
935             OCSP_basic_add1_status(bs, cid,
936                                    V_OCSP_CERTSTATUS_UNKNOWN,
937                                    0, NULL, thisupd, nextupd);
938             continue;
939         }
940         OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
941         inf = lookup_serial(db, serial);
942         if (!inf)
943             OCSP_basic_add1_status(bs, cid,
944                                    V_OCSP_CERTSTATUS_UNKNOWN,
945                                    0, NULL, thisupd, nextupd);
946         else if (inf[DB_type][0] == DB_TYPE_VAL)
947             OCSP_basic_add1_status(bs, cid,
948                                    V_OCSP_CERTSTATUS_GOOD,
949                                    0, NULL, thisupd, nextupd);
950         else if (inf[DB_type][0] == DB_TYPE_REV) {
951             ASN1_OBJECT *inst = NULL;
952             ASN1_TIME *revtm = NULL;
953             ASN1_GENERALIZEDTIME *invtm = NULL;
954             OCSP_SINGLERESP *single;
955             int reason = -1;
956             unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
957             single = OCSP_basic_add1_status(bs, cid,
958                                             V_OCSP_CERTSTATUS_REVOKED,
959                                             reason, revtm, thisupd, nextupd);
960             if (invtm)
961                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
962                                              invtm, 0, 0);
963             else if (inst)
964                 OCSP_SINGLERESP_add1_ext_i2d(single,
965                                              NID_hold_instruction_code, inst,
966                                              0, 0);
967             ASN1_OBJECT_free(inst);
968             ASN1_TIME_free(revtm);
969             ASN1_GENERALIZEDTIME_free(invtm);
970         }
971     }
972
973     OCSP_copy_nonce(bs, req);
974
975     OCSP_basic_sign(bs, rcert, rkey, rmd, rother, flags);
976
977     if (badsig) {
978         ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
979         unsigned char *sigptr = ASN1_STRING_data(sig);
980         sigptr[ASN1_STRING_length(sig) - 1] ^= 0x1;
981     }
982
983     *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
984
985  end:
986     ASN1_TIME_free(thisupd);
987     ASN1_TIME_free(nextupd);
988     OCSP_CERTID_free(ca_id);
989     OCSP_BASICRESP_free(bs);
990 }
991
992 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
993 {
994     int i;
995     BIGNUM *bn = NULL;
996     char *itmp, *row[DB_NUMBER], **rrow;
997     for (i = 0; i < DB_NUMBER; i++)
998         row[i] = NULL;
999     bn = ASN1_INTEGER_to_BN(ser, NULL);
1000     OPENSSL_assert(bn);         /* FIXME: should report an error at this
1001                                  * point and abort */
1002     if (BN_is_zero(bn))
1003         itmp = OPENSSL_strdup("00");
1004     else
1005         itmp = BN_bn2hex(bn);
1006     row[DB_serial] = itmp;
1007     BN_free(bn);
1008     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1009     OPENSSL_free(itmp);
1010     return rrow;
1011 }
1012
1013 /* Quick and dirty OCSP server: read in and parse input request */
1014
1015 static BIO *init_responder(const char *port)
1016 {
1017     BIO *acbio = NULL, *bufbio = NULL;
1018
1019 # ifdef OPENSSL_NO_SOCK
1020     BIO_printf(bio_err,
1021                "Error setting up accept BIO - sockets not supported.\n");
1022     return NULL;
1023 # endif
1024     bufbio = BIO_new(BIO_f_buffer());
1025     if (bufbio == NULL)
1026         goto err;
1027     acbio = BIO_new(BIO_s_accept());
1028     if (acbio == NULL
1029         || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1030         || BIO_set_accept_port(acbio, port) < 0) {
1031         BIO_printf(bio_err, "Error setting up accept BIO\n");
1032         ERR_print_errors(bio_err);
1033         goto err;
1034     }
1035
1036     BIO_set_accept_bios(acbio, bufbio);
1037     bufbio = NULL;
1038     if (BIO_do_accept(acbio) <= 0) {
1039         BIO_printf(bio_err, "Error starting accept\n");
1040         ERR_print_errors(bio_err);
1041         goto err;
1042     }
1043
1044     return acbio;
1045
1046  err:
1047     BIO_free_all(acbio);
1048     BIO_free(bufbio);
1049     return NULL;
1050 }
1051
1052
1053 /*
1054  * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1055  */
1056 static int urldecode(char *p)
1057 {
1058     unsigned char *out = (unsigned char *)p;
1059     unsigned char *save = out;
1060
1061     for (; *p; p++) {
1062         if (*p != '%')
1063             *out++ = *p;
1064         else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1065             *out++ = (app_hex(p[1]) << 4) | app_hex(p[2]);
1066             p += 2;
1067         }
1068         else
1069             return -1;
1070     }
1071     *out = '\0';
1072     return (int)(out - save);
1073 }
1074
1075 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio)
1076 {
1077     int len;
1078     OCSP_REQUEST *req = NULL;
1079     char inbuf[2048], reqbuf[2048];
1080     char *p, *q;
1081     BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1082
1083     if (BIO_do_accept(acbio) <= 0) {
1084         BIO_printf(bio_err, "Error accepting connection\n");
1085         ERR_print_errors(bio_err);
1086         return 0;
1087     }
1088
1089     cbio = BIO_pop(acbio);
1090     *pcbio = cbio;
1091
1092     /* Read the request line. */
1093     len = BIO_gets(cbio, reqbuf, sizeof reqbuf);
1094     if (len <= 0)
1095         return 1;
1096     if (strncmp(reqbuf, "GET ", 4) == 0) {
1097         /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1098         for (p = reqbuf + 4; *p == ' '; ++p)
1099             continue;
1100         if (*p != '/') {
1101             BIO_printf(bio_err, "Invalid request -- bad URL\n");
1102             return 1;
1103         }
1104         p++;
1105
1106         /* Splice off the HTTP version identifier. */
1107         for (q = p; *q; q++)
1108             if (*q == ' ')
1109                 break;
1110         if (strncmp(q, " HTTP/1.", 8) != 0) {
1111             BIO_printf(bio_err, "Invalid request -- bad HTTP vesion\n");
1112             return 1;
1113         }
1114         *q = '\0';
1115         len = urldecode(p);
1116         if (len <= 0) {
1117             BIO_printf(bio_err, "Invalid request -- bad URL encoding\n");
1118             return 1;
1119         }
1120         if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1121             || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1122             BIO_printf(bio_err, "Could not allocate memory\n");
1123             ERR_print_errors(bio_err);
1124             return 1;
1125         }
1126         BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1127         getbio = BIO_push(b64, getbio);
1128     } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1129         BIO_printf(bio_err, "Invalid request -- bad HTTP verb\n");
1130         return 1;
1131     }
1132
1133     /* Read and skip past the headers. */
1134     for (;;) {
1135         len = BIO_gets(cbio, inbuf, sizeof inbuf);
1136         if (len <= 0)
1137             return 1;
1138         if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1139             break;
1140     }
1141
1142     /* Try to read OCSP request */
1143     if (getbio) {
1144         req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1145         BIO_free_all(getbio);
1146     } else
1147         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1148
1149     if (!req) {
1150         BIO_printf(bio_err, "Error parsing OCSP request\n");
1151         ERR_print_errors(bio_err);
1152     }
1153
1154     *preq = req;
1155
1156     return 1;
1157
1158 }
1159
1160 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1161 {
1162     char http_resp[] =
1163         "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1164         "Content-Length: %d\r\n\r\n";
1165     if (!cbio)
1166         return 0;
1167     BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1168     i2d_OCSP_RESPONSE_bio(cbio, resp);
1169     (void)BIO_flush(cbio);
1170     return 1;
1171 }
1172
1173 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1174                                       const char *path,
1175                                       const STACK_OF(CONF_VALUE) *headers,
1176                                       OCSP_REQUEST *req, int req_timeout)
1177 {
1178     int fd;
1179     int rv;
1180     int i;
1181     int add_host = 1;
1182     OCSP_REQ_CTX *ctx = NULL;
1183     OCSP_RESPONSE *rsp = NULL;
1184     fd_set confds;
1185     struct timeval tv;
1186
1187     if (req_timeout != -1)
1188         BIO_set_nbio(cbio, 1);
1189
1190     rv = BIO_do_connect(cbio);
1191
1192     if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1193         BIO_puts(bio_err, "Error connecting BIO\n");
1194         return NULL;
1195     }
1196
1197     if (BIO_get_fd(cbio, &fd) < 0) {
1198         BIO_puts(bio_err, "Can't get connection fd\n");
1199         goto err;
1200     }
1201
1202     if (req_timeout != -1 && rv <= 0) {
1203         FD_ZERO(&confds);
1204         openssl_fdset(fd, &confds);
1205         tv.tv_usec = 0;
1206         tv.tv_sec = req_timeout;
1207         rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1208         if (rv == 0) {
1209             BIO_puts(bio_err, "Timeout on connect\n");
1210             return NULL;
1211         }
1212     }
1213
1214     ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1215     if (ctx == NULL)
1216         return NULL;
1217
1218     for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1219         CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1220         if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1221             add_host = 0;
1222         if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1223             goto err;
1224     }
1225
1226     if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1227         goto err;
1228
1229     if (!OCSP_REQ_CTX_set1_req(ctx, req))
1230         goto err;
1231
1232     for (;;) {
1233         rv = OCSP_sendreq_nbio(&rsp, ctx);
1234         if (rv != -1)
1235             break;
1236         if (req_timeout == -1)
1237             continue;
1238         FD_ZERO(&confds);
1239         openssl_fdset(fd, &confds);
1240         tv.tv_usec = 0;
1241         tv.tv_sec = req_timeout;
1242         if (BIO_should_read(cbio))
1243             rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1244         else if (BIO_should_write(cbio))
1245             rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1246         else {
1247             BIO_puts(bio_err, "Unexpected retry condition\n");
1248             goto err;
1249         }
1250         if (rv == 0) {
1251             BIO_puts(bio_err, "Timeout on request\n");
1252             break;
1253         }
1254         if (rv == -1) {
1255             BIO_puts(bio_err, "Select error\n");
1256             break;
1257         }
1258
1259     }
1260  err:
1261     OCSP_REQ_CTX_free(ctx);
1262
1263     return rsp;
1264 }
1265
1266 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1267                                  const char *host, const char *path,
1268                                  const char *port, int use_ssl,
1269                                  STACK_OF(CONF_VALUE) *headers,
1270                                  int req_timeout)
1271 {
1272     BIO *cbio = NULL;
1273     SSL_CTX *ctx = NULL;
1274     OCSP_RESPONSE *resp = NULL;
1275
1276     cbio = BIO_new_connect(host);
1277     if (!cbio) {
1278         BIO_printf(bio_err, "Error creating connect BIO\n");
1279         goto end;
1280     }
1281     if (port)
1282         BIO_set_conn_port(cbio, port);
1283     if (use_ssl == 1) {
1284         BIO *sbio;
1285         ctx = SSL_CTX_new(TLS_client_method());
1286         if (ctx == NULL) {
1287             BIO_printf(bio_err, "Error creating SSL context.\n");
1288             goto end;
1289         }
1290         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1291         sbio = BIO_new_ssl(ctx, 1);
1292         cbio = BIO_push(sbio, cbio);
1293     }
1294
1295     resp = query_responder(cbio, host, path, headers, req, req_timeout);
1296     if (!resp)
1297         BIO_printf(bio_err, "Error querying OCSP responder\n");
1298  end:
1299     BIO_free_all(cbio);
1300     SSL_CTX_free(ctx);
1301     return resp;
1302 }
1303
1304 #endif