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