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