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