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