apps/ocsp: Return non zero exit code with invalid certID
[openssl.git] / apps / ocsp.c
1 /*
2  * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/opensslconf.h>
11
12 #ifdef OPENSSL_SYS_VMS
13   /* So fd_set and friends get properly defined on OpenVMS */
14 # define _XOPEN_SOURCE_EXTENDED
15 #endif
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <time.h>
21 #include <ctype.h>
22
23 /* Needs to be included before the openssl headers */
24 #include "apps.h"
25 #include "http_server.h"
26 #include "progs.h"
27 #include "internal/sockets.h"
28 #include <openssl/e_os2.h>
29 #include <openssl/crypto.h>
30 #include <openssl/err.h>
31 #include <openssl/ssl.h>
32 #include <openssl/evp.h>
33 #include <openssl/bn.h>
34 #include <openssl/x509v3.h>
35
36 #if defined(__TANDEM)
37 # if defined(OPENSSL_TANDEM_FLOSS)
38 #  include <floss.h(floss_fork)>
39 # endif
40 #endif
41
42 #if defined(OPENSSL_SYS_VXWORKS)
43 /* not supported */
44 int setpgid(pid_t pid, pid_t pgid)
45 {
46     errno = ENOSYS;
47     return 0;
48 }
49 /* not supported */
50 pid_t fork(void)
51 {
52     errno = ENOSYS;
53     return (pid_t) -1;
54 }
55 #endif
56 /* Maximum leeway in validity period: default 5 minutes */
57 #define MAX_VALIDITY_PERIOD    (5 * 60)
58
59 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
60                          const EVP_MD *cert_id_md, X509 *issuer,
61                          STACK_OF(OCSP_CERTID) *ids);
62 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
63                            const EVP_MD *cert_id_md, X509 *issuer,
64                            STACK_OF(OCSP_CERTID) *ids);
65 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
66                               STACK_OF(OPENSSL_STRING) *names,
67                               STACK_OF(OCSP_CERTID) *ids, long nsec,
68                               long maxage);
69 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
70                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
71                               EVP_PKEY *rkey, const EVP_MD *md,
72                               STACK_OF(OPENSSL_STRING) *sigopts,
73                               STACK_OF(X509) *rother, unsigned long flags,
74                               int nmin, int ndays, int badsig,
75                               const EVP_MD *resp_md);
76
77 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
78 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
79                         int timeout);
80 static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp);
81 static char *prog;
82
83 #ifdef HTTP_DAEMON
84 static int index_changed(CA_DB *);
85 #endif
86
87 typedef enum OPTION_choice {
88     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
89     OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
90     OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
91     OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
92     OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
93     OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
94     OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
95     OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
96     OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE,
97     OPT_NOCAPATH, OPT_NOCASTORE,
98     OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
99     OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
100     OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
101     OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
102     OPT_PASSIN,
103     OPT_RCID,
104     OPT_V_ENUM,
105     OPT_MD,
106     OPT_MULTI, OPT_PROV_ENUM
107 } OPTION_CHOICE;
108
109 const OPTIONS ocsp_options[] = {
110     OPT_SECTION("General"),
111     {"help", OPT_HELP, '-', "Display this summary"},
112     {"ignore_err", OPT_IGNORE_ERR, '-',
113      "Ignore error on OCSP request or response and continue running"},
114     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
115     {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
116     {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
117     {"no-CAfile", OPT_NOCAFILE, '-',
118      "Do not load the default certificates file"},
119     {"no-CApath", OPT_NOCAPATH, '-',
120      "Do not load certificates from the default certificates directory"},
121     {"no-CAstore", OPT_NOCASTORE, '-',
122      "Do not load certificates from the default certificates store"},
123
124     OPT_SECTION("Responder"),
125     {"timeout", OPT_TIMEOUT, 'p',
126      "Connection timeout (in seconds) to the OCSP responder"},
127     {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
128      "Don't include any certificates in response"},
129 #ifdef HTTP_DAEMON
130     {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
131 #endif
132     {"no_certs", OPT_NO_CERTS, '-',
133      "Don't include any certificates in signed request"},
134     {"badsig", OPT_BADSIG, '-',
135         "Corrupt last byte of loaded OSCP response signature (for test)"},
136     {"CA", OPT_CA, '<', "CA certificate"},
137     {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
138     {"nrequest", OPT_REQUEST, 'p',
139      "Number of requests to accept (default unlimited)"},
140     {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
141     {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
142     {"sign_other", OPT_SIGN_OTHER, '<',
143      "Additional certificates to include in signed request"},
144     {"index", OPT_INDEX, '<', "Certificate status index file"},
145     {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
146     {"rsigner", OPT_RSIGNER, '<',
147      "Responder certificate to sign responses with"},
148     {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
149     {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"},
150     {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
151     {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
152     {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
153     {"header", OPT_HEADER, 's', "key=value header to add"},
154     {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
155     {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
156
157     OPT_SECTION("Client"),
158     {"url", OPT_URL, 's', "Responder URL"},
159     {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
160     {"port", OPT_PORT, 'p', "Port to run responder on"},
161     {"out", OPT_OUTFILE, '>', "Output filename"},
162     {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
163     {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
164     {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
165     {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
166      "Don't check signature on response"},
167     {"resp_key_id", OPT_RESP_KEY_ID, '-',
168      "Identify response by signing certificate key ID"},
169     {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
170      "Don't check signing certificate"},
171     {"text", OPT_TEXT, '-', "Print text form of request and response"},
172     {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
173     {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
174     {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
175     {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
176      "Don't do additional checks on signing certificate"},
177     {"no_explicit", OPT_NO_EXPLICIT, '-',
178      "Do not explicitly check the chain, just verify the root"},
179     {"trust_other", OPT_TRUST_OTHER, '-',
180      "Don't verify additional certificates"},
181     {"no_intern", OPT_NO_INTERN, '-',
182      "Don't search certificates contained in response for signer"},
183     {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
184     {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
185     {"verify_other", OPT_VERIFY_OTHER, '<',
186      "Additional certificates to search for signer"},
187     {"path", OPT_PATH, 's', "Path to use in OCSP request"},
188     {"cert", OPT_CERT, '<', "Certificate to check"},
189     {"serial", OPT_SERIAL, 's', "Serial number to check"},
190     {"validity_period", OPT_VALIDITY_PERIOD, 'u',
191      "Maximum validity discrepancy in seconds"},
192     {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
193     {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
194     {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
195     {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
196     {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
197
198     OPT_V_OPTIONS,
199     OPT_PROV_OPTIONS,
200     {NULL}
201 };
202
203 int ocsp_main(int argc, char **argv)
204 {
205     BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
206     const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
207     STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
208     int trailing_md = 0;
209     CA_DB *rdb = NULL;
210     EVP_PKEY *key = NULL, *rkey = NULL;
211     OCSP_BASICRESP *bs = NULL;
212     OCSP_REQUEST *req = NULL;
213     OCSP_RESPONSE *resp = NULL;
214     STACK_OF(CONF_VALUE) *headers = NULL;
215     STACK_OF(OCSP_CERTID) *ids = NULL;
216     STACK_OF(OPENSSL_STRING) *reqnames = NULL;
217     STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
218     STACK_OF(X509) *issuers = NULL;
219     X509 *issuer = NULL, *cert = NULL;
220     STACK_OF(X509) *rca_cert = NULL;
221     const EVP_MD *resp_certid_md = NULL;
222     X509 *signer = NULL, *rsigner = NULL;
223     X509_STORE *store = NULL;
224     X509_VERIFY_PARAM *vpm = NULL;
225     const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
226     char *header, *value;
227     char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
228     char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
229     char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
230     char *rsignfile = NULL, *rkeyfile = NULL;
231     char *passinarg = NULL, *passin = NULL;
232     char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
233     char *signfile = NULL, *keyfile = NULL;
234     char *thost = NULL, *tport = NULL, *tpath = NULL;
235     int noCAfile = 0, noCApath = 0, noCAstore = 0;
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, res, ret = 1;
239     int req_timeout = -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
244     reqnames = sk_OPENSSL_STRING_new_null();
245     if (reqnames == NULL)
246         goto end;
247     ids = sk_OCSP_CERTID_new_null();
248     if (ids == NULL)
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 #ifndef OPENSSL_NO_SOCK
270             req_timeout = atoi(opt_arg());
271 #endif
272             break;
273         case OPT_URL:
274             OPENSSL_free(thost);
275             OPENSSL_free(tport);
276             OPENSSL_free(tpath);
277             thost = tport = tpath = NULL;
278             if (!OSSL_HTTP_parse_url(opt_arg(),
279                                      &host, &port, NULL, &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_CASTORE:
373             CAstore = opt_arg();
374             break;
375         case OPT_NOCAFILE:
376             noCAfile = 1;
377             break;
378         case OPT_NOCAPATH:
379             noCApath = 1;
380             break;
381         case OPT_NOCASTORE:
382             noCAstore = 1;
383             break;
384         case OPT_V_CASES:
385             if (!opt_verify(o, vpm))
386                 goto end;
387             vpmtouched++;
388             break;
389         case OPT_VALIDITY_PERIOD:
390             opt_long(opt_arg(), &nsec);
391             break;
392         case OPT_STATUS_AGE:
393             opt_long(opt_arg(), &maxage);
394             break;
395         case OPT_SIGNKEY:
396             keyfile = opt_arg();
397             break;
398         case OPT_REQOUT:
399             reqout = opt_arg();
400             break;
401         case OPT_RESPOUT:
402             respout = opt_arg();
403             break;
404         case OPT_PATH:
405             path = opt_arg();
406             break;
407         case OPT_ISSUER:
408             issuer = load_cert(opt_arg(), FORMAT_UNDEF,
409                                "issuer certificate");
410             if (issuer == NULL)
411                 goto end;
412             if (issuers == NULL) {
413                 if ((issuers = sk_X509_new_null()) == NULL)
414                     goto end;
415             }
416             if (!sk_X509_push(issuers, issuer))
417                 goto end;
418             break;
419         case OPT_CERT:
420             X509_free(cert);
421             cert = load_cert(opt_arg(), FORMAT_UNDEF, "certificate");
422             if (cert == NULL)
423                 goto end;
424             if (cert_id_md == NULL)
425                 cert_id_md = EVP_sha1();
426             if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
427                 goto end;
428             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
429                 goto end;
430             trailing_md = 0;
431             break;
432         case OPT_SERIAL:
433             if (cert_id_md == NULL)
434                 cert_id_md = EVP_sha1();
435             if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
436                 goto end;
437             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
438                 goto end;
439             trailing_md = 0;
440             break;
441         case OPT_INDEX:
442             ridx_filename = opt_arg();
443             break;
444         case OPT_CA:
445             rca_filename = opt_arg();
446             break;
447         case OPT_NMIN:
448             opt_int(opt_arg(), &nmin);
449             if (ndays == -1)
450                 ndays = 0;
451             break;
452         case OPT_REQUEST:
453             opt_int(opt_arg(), &accept_count);
454             break;
455         case OPT_NDAYS:
456             ndays = atoi(opt_arg());
457             break;
458         case OPT_RSIGNER:
459             rsignfile = opt_arg();
460             break;
461         case OPT_RKEY:
462             rkeyfile = opt_arg();
463             break;
464         case OPT_PASSIN:
465             passinarg = opt_arg();
466             break;
467         case OPT_ROTHER:
468             rcertfile = opt_arg();
469             break;
470         case OPT_RMD:   /* Response MessageDigest */
471             if (!opt_md(opt_arg(), &rsign_md))
472                 goto end;
473             break;
474         case OPT_RSIGOPT:
475             if (rsign_sigopts == NULL)
476                 rsign_sigopts = sk_OPENSSL_STRING_new_null();
477             if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
478                 goto end;
479             break;
480         case OPT_HEADER:
481             header = opt_arg();
482             value = strchr(header, '=');
483             if (value == NULL) {
484                 BIO_printf(bio_err, "Missing = in header key=value\n");
485                 goto opthelp;
486             }
487             *value++ = '\0';
488             if (!X509V3_add_value(header, value, &headers))
489                 goto end;
490             break;
491         case OPT_RCID:
492             resp_certid_md = EVP_get_digestbyname(opt_arg());
493             if (resp_certid_md == NULL)
494                 goto opthelp;
495             break;
496         case OPT_MD:
497             if (trailing_md) {
498                 BIO_printf(bio_err,
499                            "%s: Digest must be before -cert or -serial\n",
500                            prog);
501                 goto opthelp;
502             }
503             if (!opt_md(opt_unknown(), &cert_id_md))
504                 goto opthelp;
505             trailing_md = 1;
506             break;
507         case OPT_MULTI:
508 #ifdef HTTP_DAEMON
509             multi = atoi(opt_arg());
510 #endif
511             break;
512         case OPT_PROV_CASES:
513             if (!opt_provider(o))
514                 goto end;
515             break;
516         }
517     }
518     if (trailing_md) {
519         BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
520                    prog);
521         goto opthelp;
522     }
523     argc = opt_num_rest();
524     if (argc != 0)
525         goto opthelp;
526
527     /* Have we anything to do? */
528     if (req == NULL && reqin == NULL
529         && respin == NULL && !(port != NULL && ridx_filename != NULL))
530         goto opthelp;
531
532     out = bio_open_default(outfile, 'w', FORMAT_TEXT);
533     if (out == NULL)
534         goto end;
535
536     if (req == NULL && (add_nonce != 2))
537         add_nonce = 0;
538
539     if (req == NULL && reqin != NULL) {
540         derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
541         if (derbio == NULL)
542             goto end;
543         req = d2i_OCSP_REQUEST_bio(derbio, NULL);
544         BIO_free(derbio);
545         if (req == NULL) {
546             BIO_printf(bio_err, "Error reading OCSP request\n");
547             goto end;
548         }
549     }
550
551     if (req == NULL && port != NULL) {
552 #ifndef OPENSSL_NO_SOCK
553         acbio = http_server_init_bio(prog, port);
554         if (acbio == NULL)
555             goto end;
556 #else
557         BIO_printf(bio_err, "Cannot act as server - sockets not supported\n");
558         goto end;
559 #endif
560     }
561
562     if (rsignfile != NULL) {
563         if (rkeyfile == NULL)
564             rkeyfile = rsignfile;
565         rsigner = load_cert(rsignfile, FORMAT_UNDEF,
566                             "responder certificate");
567         if (rsigner == NULL) {
568             BIO_printf(bio_err, "Error loading responder certificate\n");
569             goto end;
570         }
571         if (!load_certs(rca_filename, &rca_cert, NULL, "CA certificates"))
572             goto end;
573         if (rcertfile != NULL) {
574             if (!load_certs(rcertfile, &rother, NULL,
575                             "responder other certificates"))
576                 goto end;
577         }
578         if (!app_passwd(passinarg, NULL, &passin, NULL)) {
579             BIO_printf(bio_err, "Error getting password\n");
580             goto end;
581         }
582         rkey = load_key(rkeyfile, FORMAT_PEM, 0, passin, NULL,
583                         "responder private key");
584         if (rkey == NULL)
585             goto end;
586     }
587
588     if (ridx_filename != NULL
589         && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
590         BIO_printf(bio_err,
591                    "Responder mode requires certificate, key, and CA.\n");
592         goto end;
593     }
594
595     if (ridx_filename != NULL) {
596         rdb = load_index(ridx_filename, NULL);
597         if (rdb == NULL || index_index(rdb) <= 0) {
598             ret = 1;
599             goto end;
600         }
601     }
602
603 #ifdef HTTP_DAEMON
604     if (multi && acbio != NULL)
605         spawn_loop(prog);
606     if (acbio != NULL && req_timeout > 0)
607         signal(SIGALRM, socket_timeout);
608 #endif
609
610     if (acbio != NULL)
611         log_message(prog, LOG_INFO, "waiting for OCSP client connections...");
612
613 redo_accept:
614
615     if (acbio != NULL) {
616 #ifdef HTTP_DAEMON
617         if (index_changed(rdb)) {
618             CA_DB *newrdb = load_index(ridx_filename, NULL);
619
620             if (newrdb != NULL && index_index(newrdb) > 0) {
621                 free_index(rdb);
622                 rdb = newrdb;
623             } else {
624                 free_index(newrdb);
625                 log_message(prog, LOG_ERR, "error reloading updated index: %s",
626                             ridx_filename);
627             }
628         }
629 #endif
630
631         req = NULL;
632         res = do_responder(&req, &cbio, acbio, req_timeout);
633         if (res == 0)
634             goto redo_accept;
635
636         if (req == NULL) {
637             if (res == 1) {
638                 resp =
639                     OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
640                                          NULL);
641                 send_ocsp_response(cbio, resp);
642             }
643             goto done_resp;
644         }
645     }
646
647     if (req == NULL
648         && (signfile != NULL || reqout != NULL
649             || host != NULL || add_nonce || ridx_filename != NULL)) {
650         BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
651         goto end;
652     }
653
654     if (req != NULL && add_nonce) {
655         if (!OCSP_request_add1_nonce(req, NULL, -1))
656             goto end;
657     }
658
659     if (signfile != NULL) {
660         if (keyfile == NULL)
661             keyfile = signfile;
662         signer = load_cert(signfile, FORMAT_UNDEF, "signer certificate");
663         if (signer == NULL) {
664             BIO_printf(bio_err, "Error loading signer certificate\n");
665             goto end;
666         }
667         if (sign_certfile != NULL) {
668             if (!load_certs(sign_certfile, &sign_other, NULL,
669                             "signer certificates"))
670                 goto end;
671         }
672         key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
673                        "signer private key");
674         if (key == NULL)
675             goto end;
676
677         if (!OCSP_request_sign
678             (req, signer, key, NULL, sign_other, sign_flags)) {
679             BIO_printf(bio_err, "Error signing OCSP request\n");
680             goto end;
681         }
682     }
683
684     if (req_text && req != NULL)
685         OCSP_REQUEST_print(out, req, 0);
686
687     if (reqout != NULL) {
688         derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
689         if (derbio == NULL)
690             goto end;
691         i2d_OCSP_REQUEST_bio(derbio, req);
692         BIO_free(derbio);
693     }
694
695     if (rdb != NULL) {
696         make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
697                            rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
698                            resp_certid_md);
699         if (cbio != NULL)
700             send_ocsp_response(cbio, resp);
701     } else if (host != NULL) {
702 #ifndef OPENSSL_NO_SOCK
703         resp = process_responder(req, host, path,
704                                  port, use_ssl, headers, req_timeout);
705         if (resp == NULL)
706             goto end;
707 #else
708         BIO_printf(bio_err,
709                    "Error creating connect BIO - sockets not supported\n");
710         goto end;
711 #endif
712     } else if (respin != NULL) {
713         derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
714         if (derbio == NULL)
715             goto end;
716         resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
717         BIO_free(derbio);
718         if (resp == NULL) {
719             BIO_printf(bio_err, "Error reading OCSP response\n");
720             goto end;
721         }
722     } else {
723         ret = 0;
724         goto end;
725     }
726
727  done_resp:
728
729     if (respout != NULL) {
730         derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
731         if (derbio == NULL)
732             goto end;
733         i2d_OCSP_RESPONSE_bio(derbio, resp);
734         BIO_free(derbio);
735     }
736
737     i = OCSP_response_status(resp);
738     if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
739         BIO_printf(out, "Responder Error: %s (%d)\n",
740                    OCSP_response_status_str(i), i);
741         if (!ignore_err)
742                 goto end;
743     }
744
745     if (resp_text)
746         OCSP_RESPONSE_print(out, resp, 0);
747
748     /* If running as responder don't verify our own response */
749     if (cbio != NULL) {
750         /* If not unlimited, see if we took all we should. */
751         if (accept_count != -1 && --accept_count <= 0) {
752             ret = 0;
753             goto end;
754         }
755         BIO_free_all(cbio);
756         cbio = NULL;
757         OCSP_REQUEST_free(req);
758         req = NULL;
759         OCSP_RESPONSE_free(resp);
760         resp = NULL;
761         goto redo_accept;
762     }
763     if (ridx_filename != NULL) {
764         ret = 0;
765         goto end;
766     }
767
768     if (store == NULL) {
769         store = setup_verify(CAfile, noCAfile, CApath, noCApath,
770                              CAstore, noCAstore);
771         if (!store)
772             goto end;
773     }
774     if (vpmtouched)
775         X509_STORE_set1_param(store, vpm);
776     if (verify_certfile != NULL) {
777         if (!load_certs(verify_certfile, &verify_other, NULL,
778                         "validator certificates"))
779             goto end;
780     }
781
782     bs = OCSP_response_get1_basic(resp);
783     if (bs == NULL) {
784         BIO_printf(bio_err, "Error parsing response\n");
785         goto end;
786     }
787
788     ret = 0;
789
790     if (!noverify) {
791         if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
792             if (i == -1)
793                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
794             else {
795                 BIO_printf(bio_err, "Nonce Verify error\n");
796                 ret = 1;
797                 goto end;
798             }
799         }
800
801         i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
802         if (i <= 0 && issuers) {
803             i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
804             if (i > 0)
805                 ERR_clear_error();
806         }
807         if (i <= 0) {
808             BIO_printf(bio_err, "Response Verify Failure\n");
809             ERR_print_errors(bio_err);
810             ret = 1;
811         } else {
812             BIO_printf(bio_err, "Response verify OK\n");
813         }
814     }
815
816     if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
817         ret = 1;
818
819  end:
820     ERR_print_errors(bio_err);
821     X509_free(signer);
822     X509_STORE_free(store);
823     X509_VERIFY_PARAM_free(vpm);
824     sk_OPENSSL_STRING_free(rsign_sigopts);
825     EVP_PKEY_free(key);
826     EVP_PKEY_free(rkey);
827     X509_free(cert);
828     sk_X509_pop_free(issuers, X509_free);
829     X509_free(rsigner);
830     sk_X509_pop_free(rca_cert, X509_free);
831     free_index(rdb);
832     BIO_free_all(cbio);
833     BIO_free_all(acbio);
834     BIO_free_all(out);
835     OCSP_REQUEST_free(req);
836     OCSP_RESPONSE_free(resp);
837     OCSP_BASICRESP_free(bs);
838     sk_OPENSSL_STRING_free(reqnames);
839     sk_OCSP_CERTID_free(ids);
840     sk_X509_pop_free(sign_other, X509_free);
841     sk_X509_pop_free(verify_other, X509_free);
842     sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
843     OPENSSL_free(thost);
844     OPENSSL_free(tport);
845     OPENSSL_free(tpath);
846
847     return ret;
848 }
849
850 #ifdef HTTP_DAEMON
851
852 static int index_changed(CA_DB *rdb)
853 {
854     struct stat sb;
855
856     if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
857         if (rdb->dbst.st_mtime != sb.st_mtime
858             || rdb->dbst.st_ctime != sb.st_ctime
859             || rdb->dbst.st_ino != sb.st_ino
860             || rdb->dbst.st_dev != sb.st_dev) {
861             syslog(LOG_INFO, "index file changed, reloading");
862             return 1;
863         }
864     }
865     return 0;
866 }
867
868 #endif
869
870 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
871                          const EVP_MD *cert_id_md, X509 *issuer,
872                          STACK_OF(OCSP_CERTID) *ids)
873 {
874     OCSP_CERTID *id;
875
876     if (issuer == NULL) {
877         BIO_printf(bio_err, "No issuer certificate specified\n");
878         return 0;
879     }
880     if (*req == NULL)
881         *req = OCSP_REQUEST_new();
882     if (*req == NULL)
883         goto err;
884     id = OCSP_cert_to_id(cert_id_md, cert, issuer);
885     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
886         goto err;
887     if (!OCSP_request_add0_id(*req, id))
888         goto err;
889     return 1;
890
891  err:
892     BIO_printf(bio_err, "Error Creating OCSP request\n");
893     return 0;
894 }
895
896 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
897                            const EVP_MD *cert_id_md, X509 *issuer,
898                            STACK_OF(OCSP_CERTID) *ids)
899 {
900     OCSP_CERTID *id;
901     const X509_NAME *iname;
902     ASN1_BIT_STRING *ikey;
903     ASN1_INTEGER *sno;
904
905     if (issuer == NULL) {
906         BIO_printf(bio_err, "No issuer certificate specified\n");
907         return 0;
908     }
909     if (*req == NULL)
910         *req = OCSP_REQUEST_new();
911     if (*req == NULL)
912         goto err;
913     iname = X509_get_subject_name(issuer);
914     ikey = X509_get0_pubkey_bitstr(issuer);
915     sno = s2i_ASN1_INTEGER(NULL, serial);
916     if (sno == NULL) {
917         BIO_printf(bio_err, "Error converting serial number %s\n", serial);
918         return 0;
919     }
920     id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
921     ASN1_INTEGER_free(sno);
922     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
923         goto err;
924     if (!OCSP_request_add0_id(*req, id))
925         goto err;
926     return 1;
927
928  err:
929     BIO_printf(bio_err, "Error Creating OCSP request\n");
930     return 0;
931 }
932
933 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
934                               STACK_OF(OPENSSL_STRING) *names,
935                               STACK_OF(OCSP_CERTID) *ids, long nsec,
936                               long maxage)
937 {
938     OCSP_CERTID *id;
939     const char *name;
940     int i, status, reason;
941     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
942     int ret = 1;
943
944     if (req == NULL || !sk_OPENSSL_STRING_num(names))
945         return 1;
946
947     if (bs == NULL || !sk_OCSP_CERTID_num(ids))
948         return 0;
949
950     for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
951         id = sk_OCSP_CERTID_value(ids, i);
952         name = sk_OPENSSL_STRING_value(names, i);
953         BIO_printf(out, "%s: ", name);
954
955         if (!OCSP_resp_find_status(bs, id, &status, &reason,
956                                    &rev, &thisupd, &nextupd)) {
957             BIO_puts(out, "ERROR: No Status found.\n");
958             ret = 0;
959             continue;
960         }
961
962         /*
963          * Check validity: if invalid write to output BIO so we know which
964          * response this refers to.
965          */
966         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
967             BIO_puts(out, "WARNING: Status times invalid.\n");
968             ERR_print_errors(out);
969         }
970         BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
971
972         BIO_puts(out, "\tThis Update: ");
973         ASN1_GENERALIZEDTIME_print(out, thisupd);
974         BIO_puts(out, "\n");
975
976         if (nextupd) {
977             BIO_puts(out, "\tNext Update: ");
978             ASN1_GENERALIZEDTIME_print(out, nextupd);
979             BIO_puts(out, "\n");
980         }
981
982         if (status != V_OCSP_CERTSTATUS_REVOKED)
983             continue;
984
985         if (reason != -1)
986             BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
987
988         BIO_puts(out, "\tRevocation Time: ");
989         ASN1_GENERALIZEDTIME_print(out, rev);
990         BIO_puts(out, "\n");
991     }
992     return ret;
993 }
994
995 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
996                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
997                               EVP_PKEY *rkey, const EVP_MD *rmd,
998                               STACK_OF(OPENSSL_STRING) *sigopts,
999                               STACK_OF(X509) *rother, unsigned long flags,
1000                               int nmin, int ndays, int badsig,
1001                               const EVP_MD *resp_md)
1002 {
1003     ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1004     OCSP_CERTID *cid;
1005     OCSP_BASICRESP *bs = NULL;
1006     int i, id_count;
1007     EVP_MD_CTX *mctx = NULL;
1008     EVP_PKEY_CTX *pkctx = NULL;
1009
1010     id_count = OCSP_request_onereq_count(req);
1011
1012     if (id_count <= 0) {
1013         *resp =
1014             OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1015         goto end;
1016     }
1017
1018     bs = OCSP_BASICRESP_new();
1019     thisupd = X509_gmtime_adj(NULL, 0);
1020     if (ndays != -1)
1021         nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1022
1023     /* Examine each certificate id in the request */
1024     for (i = 0; i < id_count; i++) {
1025         OCSP_ONEREQ *one;
1026         ASN1_INTEGER *serial;
1027         char **inf;
1028         int jj;
1029         int found = 0;
1030         ASN1_OBJECT *cert_id_md_oid;
1031         const EVP_MD *cert_id_md;
1032         OCSP_CERTID *cid_resp_md = NULL;
1033
1034         one = OCSP_request_onereq_get0(req, i);
1035         cid = OCSP_onereq_get0_id(one);
1036
1037         OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1038
1039         cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1040         if (cert_id_md == NULL) {
1041             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1042                                          NULL);
1043             goto end;
1044         }
1045         for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1046             X509 *ca_cert = sk_X509_value(ca, jj);
1047             OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1048
1049             if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1050                 found = 1;
1051                 if (resp_md != NULL)
1052                     cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1053             }
1054             OCSP_CERTID_free(ca_id);
1055         }
1056         OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1057         inf = lookup_serial(db, serial);
1058
1059         /* at this point, we can have cid be an alias of cid_resp_md */
1060         cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1061
1062         if (!found) {
1063             OCSP_basic_add1_status(bs, cid,
1064                                    V_OCSP_CERTSTATUS_UNKNOWN,
1065                                    0, NULL, thisupd, nextupd);
1066             continue;
1067         }
1068         if (inf == NULL) {
1069             OCSP_basic_add1_status(bs, cid,
1070                                    V_OCSP_CERTSTATUS_UNKNOWN,
1071                                    0, NULL, thisupd, nextupd);
1072         } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1073             OCSP_basic_add1_status(bs, cid,
1074                                    V_OCSP_CERTSTATUS_GOOD,
1075                                    0, NULL, thisupd, nextupd);
1076         } else if (inf[DB_type][0] == DB_TYPE_REV) {
1077             ASN1_OBJECT *inst = NULL;
1078             ASN1_TIME *revtm = NULL;
1079             ASN1_GENERALIZEDTIME *invtm = NULL;
1080             OCSP_SINGLERESP *single;
1081             int reason = -1;
1082
1083             unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1084             single = OCSP_basic_add1_status(bs, cid,
1085                                             V_OCSP_CERTSTATUS_REVOKED,
1086                                             reason, revtm, thisupd, nextupd);
1087             if (invtm != NULL)
1088                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1089                                              invtm, 0, 0);
1090             else if (inst != NULL)
1091                 OCSP_SINGLERESP_add1_ext_i2d(single,
1092                                              NID_hold_instruction_code, inst,
1093                                              0, 0);
1094             ASN1_OBJECT_free(inst);
1095             ASN1_TIME_free(revtm);
1096             ASN1_GENERALIZEDTIME_free(invtm);
1097         }
1098         OCSP_CERTID_free(cid_resp_md);
1099     }
1100
1101     OCSP_copy_nonce(bs, req);
1102
1103     mctx = EVP_MD_CTX_new();
1104     if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1105         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1106         goto end;
1107     }
1108     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1109         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1110
1111         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1112             BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1113             ERR_print_errors(bio_err);
1114             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1115                                          NULL);
1116             goto end;
1117         }
1118     }
1119     if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1120         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1121         goto end;
1122     }
1123
1124     if (badsig) {
1125         const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1126         corrupt_signature(sig);
1127     }
1128
1129     *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1130
1131  end:
1132     EVP_MD_CTX_free(mctx);
1133     ASN1_TIME_free(thisupd);
1134     ASN1_TIME_free(nextupd);
1135     OCSP_BASICRESP_free(bs);
1136 }
1137
1138 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1139 {
1140     int i;
1141     BIGNUM *bn = NULL;
1142     char *itmp, *row[DB_NUMBER], **rrow;
1143     for (i = 0; i < DB_NUMBER; i++)
1144         row[i] = NULL;
1145     bn = ASN1_INTEGER_to_BN(ser, NULL);
1146     OPENSSL_assert(bn);         /* FIXME: should report an error at this
1147                                  * point and abort */
1148     if (BN_is_zero(bn))
1149         itmp = OPENSSL_strdup("00");
1150     else
1151         itmp = BN_bn2hex(bn);
1152     row[DB_serial] = itmp;
1153     BN_free(bn);
1154     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1155     OPENSSL_free(itmp);
1156     return rrow;
1157 }
1158
1159 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1160                         int timeout)
1161 {
1162 #ifndef OPENSSL_NO_SOCK
1163     return http_server_get_asn1_req(ASN1_ITEM_rptr(OCSP_RESPONSE),
1164                                     (ASN1_VALUE **)preq, NULL, pcbio, acbio,
1165                                     prog, 1 /* accept_get */, timeout);
1166 #else
1167     BIO_printf(bio_err,
1168                "Error getting OCSP request - sockets not supported\n");
1169     *preq = NULL;
1170     return 0;
1171 #endif
1172 }
1173
1174 static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp)
1175 {
1176 #ifndef OPENSSL_NO_SOCK
1177     return http_server_send_asn1_resp(cbio, "application/ocsp-response",
1178                                       ASN1_ITEM_rptr(OCSP_RESPONSE),
1179                                       (const ASN1_VALUE *)resp);
1180 #else
1181     BIO_printf(bio_err,
1182                "Error sending OCSP response - sockets not supported\n");
1183     return 0;
1184 #endif
1185 }
1186
1187 #ifndef OPENSSL_NO_SOCK
1188 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1189                                  const char *host, const char *path,
1190                                  const char *port, int use_ssl,
1191                                  STACK_OF(CONF_VALUE) *headers,
1192                                  int req_timeout)
1193 {
1194     SSL_CTX *ctx = NULL;
1195     OCSP_RESPONSE *resp = NULL;
1196
1197     if (use_ssl == 1) {
1198         ctx = SSL_CTX_new(TLS_client_method());
1199         if (ctx == NULL) {
1200             BIO_printf(bio_err, "Error creating SSL context.\n");
1201             goto end;
1202         }
1203         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1204     }
1205
1206     resp = (OCSP_RESPONSE *)
1207         app_http_post_asn1(host, port, path, NULL, NULL /* no proxy used */,
1208                            ctx, headers, "application/ocsp-request",
1209                            (ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST),
1210                            req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE));
1211
1212     if (resp == NULL)
1213         BIO_printf(bio_err, "Error querying OCSP responder\n");
1214
1215  end:
1216     SSL_CTX_free(ctx);
1217     return resp;
1218 }
1219 #endif