b6397b8f77dcbfc073c36491444624942047d664
[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                         const char *port);
120 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
121 static OCSP_RESPONSE *query_responder(BIO *cbio, 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,
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     {"url", OPT_URL, 's', "Responder URL"},
148     {"host", OPT_HOST, 's', "host:prot top to connect to"},
149     {"port", OPT_PORT, 'p', "Port to run responder on"},
150     {"ignore_err", OPT_IGNORE_ERR, '-'},
151     {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
152     {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
153     {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
154     {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
155      "Don't include any certificates in response"},
156     {"resp_key_id", OPT_RESP_KEY_ID, '-',
157      "Identify reponse by signing certificate key ID"},
158     {"no_certs", OPT_NO_CERTS, '-',
159      "Don't include any certificates in signed request"},
160     {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
161      "Don't check signature on response"},
162     {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
163      "Don't check signing certificate"},
164     {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
165     {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
166      "Don't do additional checks on signing certificate"},
167     {"no_explicit", OPT_NO_EXPLICIT, '-'},
168     {"trust_other", OPT_TRUST_OTHER, '-',
169      "Don't verify additional certificates"},
170     {"no_intern", OPT_NO_INTERN, '-',
171      "Don't search certificates contained in response for signer"},
172     {"badsig", OPT_BADSIG, '-'},
173     {"text", OPT_TEXT, '-', "Print text form of request and response"},
174     {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
175     {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
176     {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
177     {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
178     {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
179     {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
180     {"sign_other", OPT_SIGN_OTHER, '<',
181      "Additional certificates to include in signed request"},
182     {"verify_other", OPT_VERIFY_OTHER, '<',
183      "Additional certificates to search for signer"},
184     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
185     {"CApath", OPT_CAPATH, '<', "Trusted 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', "Nerial 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      "Sesponder 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'},
207     {"header", OPT_HEADER, 's', "key=value header to add"},
208     {"", OPT_MD, '-', "Any supported digest"},
209     OPT_V_OPTIONS,
210     {NULL}
211 };
212
213 int ocsp_main(int argc, char **argv)
214 {
215     BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
216     const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
217     CA_DB *rdb = NULL;
218     EVP_PKEY *key = NULL, *rkey = NULL;
219     OCSP_BASICRESP *bs = NULL;
220     OCSP_REQUEST *req = NULL;
221     OCSP_RESPONSE *resp = NULL;
222     STACK_OF(CONF_VALUE) *headers = NULL;
223     STACK_OF(OCSP_CERTID) *ids = NULL;
224     STACK_OF(OPENSSL_STRING) *reqnames = NULL;
225     STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
226     STACK_OF(X509) *issuers = NULL;
227     X509 *issuer = NULL, *cert = NULL, *rca_cert = NULL;
228     X509 *signer = NULL, *rsigner = NULL;
229     X509_STORE *store = NULL;
230     X509_VERIFY_PARAM *vpm = NULL;
231     char *CAfile = NULL, *CApath = NULL, *header, *value;
232     char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
233     char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
234     char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
235     char *rsignfile = NULL, *rkeyfile = NULL;
236     char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
237     char *signfile = NULL, *keyfile = NULL;
238     char *thost = NULL, *tport = NULL, *tpath = NULL;
239     int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
240     int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
241     int req_text = 0, resp_text = 0, req_timeout = -1, ret = 1;
242     long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
243     unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
244     OPTION_CHOICE o;
245     char *prog;
246
247     reqnames = sk_OPENSSL_STRING_new_null();
248     if (!reqnames)
249         goto end;
250     ids = sk_OCSP_CERTID_new_null();
251     if (!ids)
252         goto end;
253     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
254         return 1;
255
256     prog = opt_init(argc, argv, ocsp_options);
257     while ((o = opt_next()) != OPT_EOF) {
258         switch (o) {
259         case OPT_EOF:
260         case OPT_ERR:
261  opthelp:
262             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
263             goto end;
264         case OPT_HELP:
265             ret = 0;
266             opt_help(ocsp_options);
267             goto end;
268         case OPT_OUTFILE:
269             outfile = opt_arg();
270             break;
271         case OPT_TIMEOUT:
272             req_timeout = atoi(opt_arg());
273             break;
274         case OPT_URL:
275             OPENSSL_free(thost);
276             OPENSSL_free(tport);
277             OPENSSL_free(tpath);
278             thost = tport = tpath = NULL;
279             if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
280                 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
281                 goto end;
282             }
283             thost = host;
284             tport = port;
285             tpath = path;
286             break;
287         case OPT_HOST:
288             host = opt_arg();
289             break;
290         case OPT_PORT:
291             port = opt_arg();
292             break;
293         case OPT_IGNORE_ERR:
294             ignore_err = 1;
295             break;
296         case OPT_NOVERIFY:
297             noverify = 1;
298             break;
299         case OPT_NONCE:
300             add_nonce = 2;
301             break;
302         case OPT_NO_NONCE:
303             add_nonce = 0;
304             break;
305         case OPT_RESP_NO_CERTS:
306             rflags |= OCSP_NOCERTS;
307             break;
308         case OPT_RESP_KEY_ID:
309             rflags |= OCSP_RESPID_KEY;
310             break;
311         case OPT_NO_CERTS:
312             sign_flags |= OCSP_NOCERTS;
313             break;
314         case OPT_NO_SIGNATURE_VERIFY:
315             verify_flags |= OCSP_NOSIGS;
316             break;
317         case OPT_NO_CERT_VERIFY:
318             verify_flags |= OCSP_NOVERIFY;
319             break;
320         case OPT_NO_CHAIN:
321             verify_flags |= OCSP_NOCHAIN;
322             break;
323         case OPT_NO_CERT_CHECKS:
324             verify_flags |= OCSP_NOCHECKS;
325             break;
326         case OPT_NO_EXPLICIT:
327             verify_flags |= OCSP_NOEXPLICIT;
328             break;
329         case OPT_TRUST_OTHER:
330             verify_flags |= OCSP_TRUSTOTHER;
331             break;
332         case OPT_NO_INTERN:
333             verify_flags |= OCSP_NOINTERN;
334             break;
335         case OPT_BADSIG:
336             badsig = 1;
337             break;
338         case OPT_TEXT:
339             req_text = resp_text = 1;
340             break;
341         case OPT_REQ_TEXT:
342             req_text = 1;
343             break;
344         case OPT_RESP_TEXT:
345             resp_text = 1;
346             break;
347         case OPT_REQIN:
348             reqin = opt_arg();
349             break;
350         case OPT_RESPIN:
351             respin = opt_arg();
352             break;
353         case OPT_SIGNER:
354             signfile = opt_arg();
355             break;
356         case OPT_VAFILE:
357             verify_certfile = opt_arg();
358             verify_flags |= OCSP_TRUSTOTHER;
359             break;
360         case OPT_SIGN_OTHER:
361             sign_certfile = opt_arg();
362             break;
363         case OPT_VERIFY_OTHER:
364             verify_certfile = opt_arg();
365             break;
366         case OPT_CAFILE:
367             CAfile = opt_arg();
368             break;
369         case OPT_CAPATH:
370             CApath = opt_arg();
371             break;
372         case OPT_V_CASES:
373             if (!opt_verify(o, vpm))
374                 goto end;
375             vpmtouched++;
376             break;
377         case OPT_VALIDITY_PERIOD:
378             opt_long(opt_arg(), &nsec);
379             break;
380         case OPT_STATUS_AGE:
381             opt_long(opt_arg(), &maxage);
382             break;
383         case OPT_SIGNKEY:
384             keyfile = opt_arg();
385             break;
386         case OPT_REQOUT:
387             reqout = opt_arg();
388             break;
389         case OPT_RESPOUT:
390             respout = opt_arg();
391             break;
392         case OPT_PATH:
393             path = opt_arg();
394             break;
395         case OPT_ISSUER:
396             X509_free(issuer);
397             issuer = load_cert(opt_arg(), FORMAT_PEM,
398                                NULL, NULL, "issuer certificate");
399             if (issuer == NULL)
400                 goto end;
401             if ((issuers = sk_X509_new_null()) == NULL)
402                 goto end;
403             sk_X509_push(issuers, issuer);
404             break;
405         case OPT_CERT:
406             X509_free(cert);
407             cert = load_cert(opt_arg(), FORMAT_PEM,
408                              NULL, NULL, "certificate");
409             if (cert == NULL)
410                 goto end;
411             if (cert_id_md == NULL)
412                 cert_id_md = EVP_sha1();
413             if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
414                 goto end;
415             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
416                 goto end;
417             break;
418         case OPT_SERIAL:
419             if (cert_id_md == NULL)
420                 cert_id_md = EVP_sha1();
421             if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
422                 goto end;
423             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
424                 goto end;
425             break;
426         case OPT_INDEX:
427             ridx_filename = opt_arg();
428             break;
429         case OPT_CA:
430             rca_filename = opt_arg();
431             break;
432         case OPT_NMIN:
433             opt_int(opt_arg(), &nmin);
434             if (ndays == -1)
435                 ndays = 0;
436             break;
437         case OPT_REQUEST:
438             opt_int(opt_arg(), &accept_count);
439             break;
440         case OPT_NDAYS:
441             ndays = atoi(opt_arg());
442             break;
443         case OPT_RSIGNER:
444             rsignfile = opt_arg();
445             break;
446         case OPT_RKEY:
447             rkeyfile = opt_arg();
448             break;
449         case OPT_ROTHER:
450             rcertfile = opt_arg();
451             break;
452         case OPT_RMD:
453             if (!opt_md(opt_arg(), &rsign_md))
454                 goto end;
455             break;
456         case OPT_HEADER:
457             header = opt_arg();
458             value = strchr(header, '=');
459             if (value == NULL) {
460                 BIO_printf(bio_err, "Missing = in header key=value\n");
461                 goto opthelp;
462             }
463             *value++ = '\0';
464             if (!X509V3_add_value(header, value, &headers))
465                 goto end;
466             break;
467         case OPT_MD:
468             if (cert_id_md != NULL) {
469                 BIO_printf(bio_err,
470                            "%s: Digest must be before -cert or -serial\n",
471                            prog);
472                 goto opthelp;
473             }
474             if (!opt_md(opt_unknown(), &cert_id_md))
475                 goto opthelp;
476             break;
477         }
478     }
479     argc = opt_num_rest();
480     argv = opt_rest();
481
482     /* Have we anything to do? */
483     if (!req && !reqin && !respin && !(port && ridx_filename))
484         goto opthelp;
485
486     if (!app_load_modules(NULL))
487         goto end;
488
489     out = bio_open_default(outfile, "w");
490     if (out == NULL)
491         goto end;
492
493     if (!req && (add_nonce != 2))
494         add_nonce = 0;
495
496     if (!req && reqin) {
497         derbio = bio_open_default(reqin, "rb");
498         if (derbio == NULL)
499             goto end;
500         req = d2i_OCSP_REQUEST_bio(derbio, NULL);
501         BIO_free(derbio);
502         if (!req) {
503             BIO_printf(bio_err, "Error reading OCSP request\n");
504             goto end;
505         }
506     }
507
508     if (!req && port) {
509         acbio = init_responder(port);
510         if (!acbio)
511             goto end;
512     }
513
514     if (rsignfile && !rdb) {
515         if (!rkeyfile)
516             rkeyfile = rsignfile;
517         rsigner = load_cert(rsignfile, FORMAT_PEM,
518                             NULL, NULL, "responder certificate");
519         if (!rsigner) {
520             BIO_printf(bio_err, "Error loading responder certificate\n");
521             goto end;
522         }
523         rca_cert = load_cert(rca_filename, FORMAT_PEM,
524                              NULL, NULL, "CA certificate");
525         if (rcertfile) {
526             rother = load_certs(rcertfile, FORMAT_PEM,
527                                 NULL, NULL, "responder other certificates");
528             if (!rother)
529                 goto end;
530         }
531         rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
532                         "responder private key");
533         if (!rkey)
534             goto end;
535     }
536     if (acbio)
537         BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
538
539  redo_accept:
540
541     if (acbio) {
542         if (!do_responder(&req, &cbio, acbio, port))
543             goto end;
544         if (!req) {
545             resp =
546                 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
547                                      NULL);
548             send_ocsp_response(cbio, resp);
549             goto done_resp;
550         }
551     }
552
553     if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
554         BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
555         goto end;
556     }
557
558     if (req && add_nonce)
559         OCSP_request_add1_nonce(req, NULL, -1);
560
561     if (signfile) {
562         if (!keyfile)
563             keyfile = signfile;
564         signer = load_cert(signfile, FORMAT_PEM,
565                            NULL, NULL, "signer certificate");
566         if (!signer) {
567             BIO_printf(bio_err, "Error loading signer certificate\n");
568             goto end;
569         }
570         if (sign_certfile) {
571             sign_other = load_certs(sign_certfile, FORMAT_PEM,
572                                     NULL, NULL, "signer certificates");
573             if (!sign_other)
574                 goto end;
575         }
576         key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
577                        "signer private key");
578         if (!key)
579             goto end;
580
581         if (!OCSP_request_sign
582             (req, signer, key, NULL, sign_other, sign_flags)) {
583             BIO_printf(bio_err, "Error signing OCSP request\n");
584             goto end;
585         }
586     }
587
588     if (req_text && req)
589         OCSP_REQUEST_print(out, req, 0);
590
591     if (reqout) {
592         derbio = bio_open_default(reqout, "wb");
593         if (derbio == NULL)
594             goto end;
595         i2d_OCSP_REQUEST_bio(derbio, req);
596         BIO_free(derbio);
597     }
598
599     if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
600         BIO_printf(bio_err,
601                    "Need a responder certificate, key and CA for this operation!\n");
602         goto end;
603     }
604
605     if (ridx_filename && !rdb) {
606         rdb = load_index(ridx_filename, NULL);
607         if (!rdb)
608             goto end;
609         if (!index_index(rdb))
610             goto end;
611     }
612
613     if (rdb) {
614         make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey,
615                                rsign_md, rother, rflags, nmin, ndays, badsig);
616         if (cbio)
617             send_ocsp_response(cbio, resp);
618     } else if (host) {
619 # ifndef OPENSSL_NO_SOCK
620         resp = process_responder(req, host, path,
621                                  port, use_ssl, headers, req_timeout);
622         if (!resp)
623             goto end;
624 # else
625         BIO_printf(bio_err,
626                    "Error creating connect BIO - sockets not supported.\n");
627         goto end;
628 # endif
629     } else if (respin) {
630         derbio = bio_open_default(respin, "rb");
631         if (derbio == NULL)
632             goto end;
633         resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
634         BIO_free(derbio);
635         if (!resp) {
636             BIO_printf(bio_err, "Error reading OCSP response\n");
637             goto end;
638         }
639     } else {
640         ret = 0;
641         goto end;
642     }
643
644  done_resp:
645
646     if (respout) {
647         derbio = bio_open_default(respout, "wb");
648         if (derbio == NULL)
649             goto end;
650         i2d_OCSP_RESPONSE_bio(derbio, resp);
651         BIO_free(derbio);
652     }
653
654     i = OCSP_response_status(resp);
655     if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
656         BIO_printf(out, "Responder Error: %s (%d)\n",
657                    OCSP_response_status_str(i), i);
658         if (ignore_err)
659             goto redo_accept;
660         ret = 0;
661         goto end;
662     }
663
664     if (resp_text)
665         OCSP_RESPONSE_print(out, resp, 0);
666
667     /* If running as responder don't verify our own response */
668     if (cbio) {
669         if (--accept_count <= 0) {
670             ret = 0;
671             goto end;
672         }
673         BIO_free_all(cbio);
674         cbio = NULL;
675         OCSP_REQUEST_free(req);
676         req = NULL;
677         OCSP_RESPONSE_free(resp);
678         resp = NULL;
679         goto redo_accept;
680     }
681     if (ridx_filename) {
682         ret = 0;
683         goto end;
684     }
685
686     if (!store) {
687         store = setup_verify(CAfile, CApath);
688         if (!store)
689             goto end;
690     }
691     if (vpmtouched)
692         X509_STORE_set1_param(store, vpm);
693     if (verify_certfile) {
694         verify_other = load_certs(verify_certfile, FORMAT_PEM,
695                                   NULL, NULL, "validator certificate");
696         if (!verify_other)
697             goto end;
698     }
699
700     bs = OCSP_response_get1_basic(resp);
701     if (!bs) {
702         BIO_printf(bio_err, "Error parsing response\n");
703         goto end;
704     }
705
706     ret = 0;
707
708     if (!noverify) {
709         if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
710             if (i == -1)
711                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
712             else {
713                 BIO_printf(bio_err, "Nonce Verify error\n");
714                 ret = 1;
715                 goto end;
716             }
717         }
718
719         i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
720         if (i <= 0 && issuers) {
721             i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
722             if (i > 0)
723                 ERR_clear_error();
724         }
725         if (i <= 0) {
726             BIO_printf(bio_err, "Response Verify Failure\n");
727             ERR_print_errors(bio_err);
728             ret = 1;
729         } else
730             BIO_printf(bio_err, "Response verify OK\n");
731
732     }
733
734     print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
735
736  end:
737     ERR_print_errors(bio_err);
738     X509_free(signer);
739     X509_STORE_free(store);
740     X509_VERIFY_PARAM_free(vpm);
741     EVP_PKEY_free(key);
742     EVP_PKEY_free(rkey);
743     X509_free(cert);
744     X509_free(rsigner);
745     X509_free(rca_cert);
746     free_index(rdb);
747     BIO_free_all(cbio);
748     BIO_free_all(acbio);
749     BIO_free(out);
750     OCSP_REQUEST_free(req);
751     OCSP_RESPONSE_free(resp);
752     OCSP_BASICRESP_free(bs);
753     sk_OPENSSL_STRING_free(reqnames);
754     sk_OCSP_CERTID_free(ids);
755     sk_X509_pop_free(sign_other, X509_free);
756     sk_X509_pop_free(verify_other, X509_free);
757     sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
758     OPENSSL_free(thost);
759     OPENSSL_free(tport);
760     OPENSSL_free(tpath);
761
762     return (ret);
763 }
764
765 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
766                          const EVP_MD *cert_id_md, X509 *issuer,
767                          STACK_OF(OCSP_CERTID) *ids)
768 {
769     OCSP_CERTID *id;
770     if (!issuer) {
771         BIO_printf(bio_err, "No issuer certificate specified\n");
772         return 0;
773     }
774     if (!*req)
775         *req = OCSP_REQUEST_new();
776     if (!*req)
777         goto err;
778     id = OCSP_cert_to_id(cert_id_md, cert, issuer);
779     if (!id || !sk_OCSP_CERTID_push(ids, id))
780         goto err;
781     if (!OCSP_request_add0_id(*req, id))
782         goto err;
783     return 1;
784
785  err:
786     BIO_printf(bio_err, "Error Creating OCSP request\n");
787     return 0;
788 }
789
790 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
791                            const EVP_MD *cert_id_md, X509 *issuer,
792                            STACK_OF(OCSP_CERTID) *ids)
793 {
794     OCSP_CERTID *id;
795     X509_NAME *iname;
796     ASN1_BIT_STRING *ikey;
797     ASN1_INTEGER *sno;
798     if (!issuer) {
799         BIO_printf(bio_err, "No issuer certificate specified\n");
800         return 0;
801     }
802     if (!*req)
803         *req = OCSP_REQUEST_new();
804     if (!*req)
805         goto err;
806     iname = X509_get_subject_name(issuer);
807     ikey = X509_get0_pubkey_bitstr(issuer);
808     sno = s2i_ASN1_INTEGER(NULL, serial);
809     if (!sno) {
810         BIO_printf(bio_err, "Error converting serial number %s\n", serial);
811         return 0;
812     }
813     id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
814     ASN1_INTEGER_free(sno);
815     if (!id || !sk_OCSP_CERTID_push(ids, id))
816         goto err;
817     if (!OCSP_request_add0_id(*req, id))
818         goto err;
819     return 1;
820
821  err:
822     BIO_printf(bio_err, "Error Creating OCSP request\n");
823     return 0;
824 }
825
826 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
827                               STACK_OF(OPENSSL_STRING) *names,
828                               STACK_OF(OCSP_CERTID) *ids, long nsec,
829                               long maxage)
830 {
831     OCSP_CERTID *id;
832     char *name;
833     int i, status, reason;
834     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
835
836     if (!bs || !req || !sk_OPENSSL_STRING_num(names)
837         || !sk_OCSP_CERTID_num(ids))
838         return;
839
840     for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
841         id = sk_OCSP_CERTID_value(ids, i);
842         name = sk_OPENSSL_STRING_value(names, i);
843         BIO_printf(out, "%s: ", name);
844
845         if (!OCSP_resp_find_status(bs, id, &status, &reason,
846                                    &rev, &thisupd, &nextupd)) {
847             BIO_puts(out, "ERROR: No Status found.\n");
848             continue;
849         }
850
851         /*
852          * Check validity: if invalid write to output BIO so we know which
853          * response this refers to.
854          */
855         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
856             BIO_puts(out, "WARNING: Status times invalid.\n");
857             ERR_print_errors(out);
858         }
859         BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
860
861         BIO_puts(out, "\tThis Update: ");
862         ASN1_GENERALIZEDTIME_print(out, thisupd);
863         BIO_puts(out, "\n");
864
865         if (nextupd) {
866             BIO_puts(out, "\tNext Update: ");
867             ASN1_GENERALIZEDTIME_print(out, nextupd);
868             BIO_puts(out, "\n");
869         }
870
871         if (status != V_OCSP_CERTSTATUS_REVOKED)
872             continue;
873
874         if (reason != -1)
875             BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
876
877         BIO_puts(out, "\tRevocation Time: ");
878         ASN1_GENERALIZEDTIME_print(out, rev);
879         BIO_puts(out, "\n");
880     }
881 }
882
883 static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req,
884                               CA_DB *db, X509 *ca, X509 *rcert,
885                               EVP_PKEY *rkey, const EVP_MD *rmd,
886                               STACK_OF(X509) *rother, unsigned long flags,
887                               int nmin, int ndays, int badsig)
888 {
889     ASN1_TIME *thisupd = NULL, *nextupd = NULL;
890     OCSP_CERTID *cid, *ca_id = NULL;
891     OCSP_BASICRESP *bs = NULL;
892     int i, id_count;
893
894     id_count = OCSP_request_onereq_count(req);
895
896     if (id_count <= 0) {
897         *resp =
898             OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
899         goto end;
900     }
901
902     bs = OCSP_BASICRESP_new();
903     thisupd = X509_gmtime_adj(NULL, 0);
904     if (ndays != -1)
905         nextupd = X509_gmtime_adj(NULL, nmin * 60 + ndays * 3600 * 24);
906
907     /* Examine each certificate id in the request */
908     for (i = 0; i < id_count; i++) {
909         OCSP_ONEREQ *one;
910         ASN1_INTEGER *serial;
911         char **inf;
912         ASN1_OBJECT *cert_id_md_oid;
913         const EVP_MD *cert_id_md;
914         one = OCSP_request_onereq_get0(req, i);
915         cid = OCSP_onereq_get0_id(one);
916
917         OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
918
919         cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
920         if (!cert_id_md) {
921             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
922                                          NULL);
923             goto end;
924         }
925         OCSP_CERTID_free(ca_id);
926         ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca);
927
928         /* Is this request about our CA? */
929         if (OCSP_id_issuer_cmp(ca_id, cid)) {
930             OCSP_basic_add1_status(bs, cid,
931                                    V_OCSP_CERTSTATUS_UNKNOWN,
932                                    0, NULL, thisupd, nextupd);
933             continue;
934         }
935         OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
936         inf = lookup_serial(db, serial);
937         if (!inf)
938             OCSP_basic_add1_status(bs, cid,
939                                    V_OCSP_CERTSTATUS_UNKNOWN,
940                                    0, NULL, thisupd, nextupd);
941         else if (inf[DB_type][0] == DB_TYPE_VAL)
942             OCSP_basic_add1_status(bs, cid,
943                                    V_OCSP_CERTSTATUS_GOOD,
944                                    0, NULL, thisupd, nextupd);
945         else if (inf[DB_type][0] == DB_TYPE_REV) {
946             ASN1_OBJECT *inst = NULL;
947             ASN1_TIME *revtm = NULL;
948             ASN1_GENERALIZEDTIME *invtm = NULL;
949             OCSP_SINGLERESP *single;
950             int reason = -1;
951             unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
952             single = OCSP_basic_add1_status(bs, cid,
953                                             V_OCSP_CERTSTATUS_REVOKED,
954                                             reason, revtm, thisupd, nextupd);
955             if (invtm)
956                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
957                                              invtm, 0, 0);
958             else if (inst)
959                 OCSP_SINGLERESP_add1_ext_i2d(single,
960                                              NID_hold_instruction_code, inst,
961                                              0, 0);
962             ASN1_OBJECT_free(inst);
963             ASN1_TIME_free(revtm);
964             ASN1_GENERALIZEDTIME_free(invtm);
965         }
966     }
967
968     OCSP_copy_nonce(bs, req);
969
970     OCSP_basic_sign(bs, rcert, rkey, rmd, rother, flags);
971
972     if (badsig) {
973         ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
974         unsigned char *sigptr = ASN1_STRING_data(sig);
975         sigptr[ASN1_STRING_length(sig) - 1] ^= 0x1;
976     }
977
978     *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
979
980  end:
981     ASN1_TIME_free(thisupd);
982     ASN1_TIME_free(nextupd);
983     OCSP_CERTID_free(ca_id);
984     OCSP_BASICRESP_free(bs);
985 }
986
987 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
988 {
989     int i;
990     BIGNUM *bn = NULL;
991     char *itmp, *row[DB_NUMBER], **rrow;
992     for (i = 0; i < DB_NUMBER; i++)
993         row[i] = NULL;
994     bn = ASN1_INTEGER_to_BN(ser, NULL);
995     OPENSSL_assert(bn);         /* FIXME: should report an error at this
996                                  * point and abort */
997     if (BN_is_zero(bn))
998         itmp = BUF_strdup("00");
999     else
1000         itmp = BN_bn2hex(bn);
1001     row[DB_serial] = itmp;
1002     BN_free(bn);
1003     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1004     OPENSSL_free(itmp);
1005     return rrow;
1006 }
1007
1008 /* Quick and dirty OCSP server: read in and parse input request */
1009
1010 static BIO *init_responder(const char *port)
1011 {
1012     BIO *acbio = NULL, *bufbio = NULL;
1013
1014 # ifdef OPENSSL_NO_SOCK
1015     BIO_printf(bio_err,
1016                "Error setting up accept BIO - sockets not supported.\n");
1017     return NULL;
1018 # endif
1019     bufbio = BIO_new(BIO_f_buffer());
1020     if (!bufbio)
1021         goto err;
1022     acbio = BIO_new(BIO_s_accept());
1023     if (acbio == NULL
1024         || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1025         || BIO_set_accept_port(acbio, port) < 0) {
1026         BIO_printf(bio_err, "Error setting up accept BIO\n");
1027         ERR_print_errors(bio_err);
1028         goto err;
1029     }
1030
1031     BIO_set_accept_bios(acbio, bufbio);
1032     bufbio = NULL;
1033     if (BIO_do_accept(acbio) <= 0) {
1034         BIO_printf(bio_err, "Error starting accept\n");
1035         ERR_print_errors(bio_err);
1036         goto err;
1037     }
1038
1039     return acbio;
1040
1041  err:
1042     BIO_free_all(acbio);
1043     BIO_free(bufbio);
1044     return NULL;
1045 }
1046
1047
1048 /*
1049  * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1050  */
1051 static int urldecode(char *p)
1052 {
1053     unsigned char *out = (unsigned char *)p;
1054     unsigned char *save = out;
1055
1056     for (; *p; p++) {
1057         if (*p != '%')
1058             *out++ = *p;
1059         else if (isxdigit(p[1]) && isxdigit(p[2])) {
1060             *out++ = (app_hex(p[1]) << 4) | app_hex(p[2]);
1061             p += 2;
1062         }
1063         else
1064             return -1;
1065     }
1066     *out = '\0';
1067     return (int)(out - save);
1068 }
1069
1070 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1071                         const char *port)
1072 {
1073     int len;
1074     OCSP_REQUEST *req = NULL;
1075     char inbuf[2048], reqbuf[2048];
1076     char *p, *q;
1077     BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1078
1079     if (BIO_do_accept(acbio) <= 0) {
1080         BIO_printf(bio_err, "Error accepting connection\n");
1081         ERR_print_errors(bio_err);
1082         return 0;
1083     }
1084
1085     cbio = BIO_pop(acbio);
1086     *pcbio = cbio;
1087
1088     /* Read the request line. */
1089     len = BIO_gets(cbio, reqbuf, sizeof reqbuf);
1090     if (len <= 0)
1091         return 1;
1092     if (strncmp(reqbuf, "GET ", 4) == 0) {
1093         /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1094         for (p = reqbuf + 4; *p == ' '; ++p)
1095             continue;
1096         if (*p != '/') {
1097             BIO_printf(bio_err, "Invalid request -- bad URL\n");
1098             return 1;
1099         }
1100         p++;
1101
1102         /* Splice off the HTTP version identifier. */
1103         for (q = p; *q; q++)
1104             if (*q == ' ')
1105                 break;
1106         if (strncmp(q, " HTTP/1.", 8) != 0) {
1107             BIO_printf(bio_err, "Invalid request -- bad HTTP vesion\n");
1108             return 1;
1109         }
1110         *q = '\0';
1111         len = urldecode(p);
1112         if (len <= 0) {
1113             BIO_printf(bio_err, "Invalid request -- bad URL encoding\n");
1114             return 1;
1115         }
1116         if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1117             || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1118             BIO_printf(bio_err, "Could not allocate memory\n");
1119             ERR_print_errors(bio_err);
1120             return 1;
1121         }
1122         BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1123         getbio = BIO_push(b64, getbio);
1124     } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1125         BIO_printf(bio_err, "Invalid request -- bad HTTP verb\n");
1126         return 1;
1127     }
1128
1129     /* Read and skip past the headers. */
1130     for (;;) {
1131         len = BIO_gets(cbio, inbuf, sizeof inbuf);
1132         if (len <= 0)
1133             return 1;
1134         if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1135             break;
1136     }
1137
1138     /* Try to read OCSP request */
1139     if (getbio) {
1140         req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1141         BIO_free_all(getbio);
1142     } else
1143         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1144
1145     if (!req) {
1146         BIO_printf(bio_err, "Error parsing OCSP request\n");
1147         ERR_print_errors(bio_err);
1148     }
1149
1150     *preq = req;
1151
1152     return 1;
1153
1154 }
1155
1156 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1157 {
1158     char http_resp[] =
1159         "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1160         "Content-Length: %d\r\n\r\n";
1161     if (!cbio)
1162         return 0;
1163     BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1164     i2d_OCSP_RESPONSE_bio(cbio, resp);
1165     (void)BIO_flush(cbio);
1166     return 1;
1167 }
1168
1169 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *path,
1170                                       const STACK_OF(CONF_VALUE) *headers,
1171                                       OCSP_REQUEST *req, int req_timeout)
1172 {
1173     int fd;
1174     int rv;
1175     int i;
1176     OCSP_REQ_CTX *ctx = NULL;
1177     OCSP_RESPONSE *rsp = NULL;
1178     fd_set confds;
1179     struct timeval tv;
1180
1181     if (req_timeout != -1)
1182         BIO_set_nbio(cbio, 1);
1183
1184     rv = BIO_do_connect(cbio);
1185
1186     if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1187         BIO_puts(bio_err, "Error connecting BIO\n");
1188         return NULL;
1189     }
1190
1191     if (BIO_get_fd(cbio, &fd) <= 0) {
1192         BIO_puts(bio_err, "Can't get connection fd\n");
1193         goto err;
1194     }
1195
1196     if (req_timeout != -1 && rv <= 0) {
1197         FD_ZERO(&confds);
1198         openssl_fdset(fd, &confds);
1199         tv.tv_usec = 0;
1200         tv.tv_sec = req_timeout;
1201         rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1202         if (rv == 0) {
1203             BIO_puts(bio_err, "Timeout on connect\n");
1204             return NULL;
1205         }
1206     }
1207
1208     ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1209     if (!ctx)
1210         return NULL;
1211
1212     for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1213         CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1214         if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1215             goto err;
1216     }
1217
1218     if (!OCSP_REQ_CTX_set1_req(ctx, req))
1219         goto err;
1220
1221     for (;;) {
1222         rv = OCSP_sendreq_nbio(&rsp, ctx);
1223         if (rv != -1)
1224             break;
1225         if (req_timeout == -1)
1226             continue;
1227         FD_ZERO(&confds);
1228         openssl_fdset(fd, &confds);
1229         tv.tv_usec = 0;
1230         tv.tv_sec = req_timeout;
1231         if (BIO_should_read(cbio))
1232             rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1233         else if (BIO_should_write(cbio))
1234             rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1235         else {
1236             BIO_puts(bio_err, "Unexpected retry condition\n");
1237             goto err;
1238         }
1239         if (rv == 0) {
1240             BIO_puts(bio_err, "Timeout on request\n");
1241             break;
1242         }
1243         if (rv == -1) {
1244             BIO_puts(bio_err, "Select error\n");
1245             break;
1246         }
1247
1248     }
1249  err:
1250     OCSP_REQ_CTX_free(ctx);
1251
1252     return rsp;
1253 }
1254
1255 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1256                                  const char *host, const char *path,
1257                                  const char *port, int use_ssl,
1258                                  const STACK_OF(CONF_VALUE) *headers,
1259                                  int req_timeout)
1260 {
1261     BIO *cbio = NULL;
1262     SSL_CTX *ctx = NULL;
1263     OCSP_RESPONSE *resp = NULL;
1264     cbio = BIO_new_connect(host);
1265     if (!cbio) {
1266         BIO_printf(bio_err, "Error creating connect BIO\n");
1267         goto end;
1268     }
1269     if (port)
1270         BIO_set_conn_port(cbio, port);
1271     if (use_ssl == 1) {
1272         BIO *sbio;
1273         ctx = SSL_CTX_new(TLS_client_method());
1274         if (ctx == NULL) {
1275             BIO_printf(bio_err, "Error creating SSL context.\n");
1276             goto end;
1277         }
1278         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1279         sbio = BIO_new_ssl(ctx, 1);
1280         cbio = BIO_push(sbio, cbio);
1281     }
1282     resp = query_responder(cbio, path, headers, req, req_timeout);
1283     if (!resp)
1284         BIO_printf(bio_err, "Error querying OCSP responder\n");
1285  end:
1286     BIO_free_all(cbio);
1287     SSL_CTX_free(ctx);
1288     return resp;
1289 }
1290
1291 #endif