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