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