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