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