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