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