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