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