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