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