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