Modify OCSP to use alt MD for cert IDs in responses
[openssl.git] / apps / ocsp.c
1 /*
2  * Copyright 2001-2018 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_NO_OCSP
13 NON_EMPTY_TRANSLATION_UNIT
14 #else
15 # ifdef OPENSSL_SYS_VMS
16 #  define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
17                                  * on OpenVMS */
18 # endif
19
20 # include <stdio.h>
21 # include <stdlib.h>
22 # include <string.h>
23 # include <time.h>
24 # include <ctype.h>
25
26 /* Needs to be included before the openssl headers */
27 # include "apps.h"
28 # include "progs.h"
29 # include "internal/sockets.h"
30 # include <openssl/e_os2.h>
31 # include <openssl/crypto.h>
32 # include <openssl/err.h>
33 # include <openssl/ssl.h>
34 # include <openssl/evp.h>
35 # include <openssl/bn.h>
36 # include <openssl/x509v3.h>
37 # include <openssl/rand.h>
38
39 #ifndef HAVE_FORK
40 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
41 #  define HAVE_FORK 0
42 # else
43 #  define HAVE_FORK 1
44 # endif
45 #endif
46
47 #if HAVE_FORK
48 # undef NO_FORK
49 #else
50 # define NO_FORK
51 #endif
52
53 # if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
54      && !defined(OPENSSL_NO_POSIX_IO)
55 #  define OCSP_DAEMON
56 #  include <sys/types.h>
57 #  include <sys/wait.h>
58 #  include <syslog.h>
59 #  include <signal.h>
60 #  define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
61 # else
62 #  undef LOG_INFO
63 #  undef LOG_WARNING
64 #  undef LOG_ERR
65 #  define LOG_INFO      0
66 #  define LOG_WARNING   1
67 #  define LOG_ERR       2
68 # endif
69
70 # if defined(OPENSSL_SYS_VXWORKS)
71 /* not supported */
72 int setpgid(pid_t pid, pid_t pgid)
73 {
74     errno = ENOSYS;
75     return 0;
76 }
77 /* not supported */
78 pid_t fork(void)
79 {
80     errno = ENOSYS;
81     return (pid_t) -1;
82 }
83 # endif
84 /* Maximum leeway in validity period: default 5 minutes */
85 # define MAX_VALIDITY_PERIOD    (5 * 60)
86
87 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
88                          const EVP_MD *cert_id_md, X509 *issuer,
89                          STACK_OF(OCSP_CERTID) *ids);
90 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
91                            const EVP_MD *cert_id_md, X509 *issuer,
92                            STACK_OF(OCSP_CERTID) *ids);
93 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
94                               STACK_OF(OPENSSL_STRING) *names,
95                               STACK_OF(OCSP_CERTID) *ids, long nsec,
96                               long maxage);
97 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
98                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
99                               EVP_PKEY *rkey, const EVP_MD *md,
100                               STACK_OF(OPENSSL_STRING) *sigopts,
101                               STACK_OF(X509) *rother, unsigned long flags,
102                               int nmin, int ndays, int badsig,
103                               const EVP_MD *resp_md);
104
105 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
106 static BIO *init_responder(const char *port);
107 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
108 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
109 static void log_message(int level, const char *fmt, ...);
110 static char *prog;
111 static int multi = 0;
112
113 # ifdef OCSP_DAEMON
114 static int acfd = (int) INVALID_SOCKET;
115 static int index_changed(CA_DB *);
116 static void spawn_loop(void);
117 static int print_syslog(const char *str, size_t len, void *levPtr);
118 static void sock_timeout(int signum);
119 # endif
120
121 # ifndef OPENSSL_NO_SOCK
122 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
123                                       const char *path,
124                                       const STACK_OF(CONF_VALUE) *headers,
125                                       OCSP_REQUEST *req, int req_timeout);
126 # endif
127
128 typedef enum OPTION_choice {
129     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
130     OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
131     OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
132     OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
133     OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
134     OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
135     OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
136     OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
137     OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH,
138     OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
139     OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
140     OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
141     OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
142     OPT_RCID,
143     OPT_V_ENUM,
144     OPT_MD,
145     OPT_MULTI
146 } OPTION_CHOICE;
147
148 const OPTIONS ocsp_options[] = {
149     {"help", OPT_HELP, '-', "Display this summary"},
150     {"out", OPT_OUTFILE, '>', "Output filename"},
151     {"timeout", OPT_TIMEOUT, 'p',
152      "Connection timeout (in seconds) to the OCSP responder"},
153     {"url", OPT_URL, 's', "Responder URL"},
154     {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
155     {"port", OPT_PORT, 'p', "Port to run responder on"},
156     {"ignore_err", OPT_IGNORE_ERR, '-',
157      "Ignore error on OCSP request or response and continue running"},
158     {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
159     {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
160     {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
161     {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
162      "Don't include any certificates in response"},
163     {"resp_key_id", OPT_RESP_KEY_ID, '-',
164      "Identify response by signing certificate key ID"},
165 # ifdef OCSP_DAEMON
166     {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
167 # endif
168     {"no_certs", OPT_NO_CERTS, '-',
169      "Don't include any certificates in signed request"},
170     {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
171      "Don't check signature on response"},
172     {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
173      "Don't check signing certificate"},
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     {"badsig", OPT_BADSIG, '-',
184         "Corrupt last byte of loaded OSCP response signature (for test)"},
185     {"text", OPT_TEXT, '-', "Print text form of request and response"},
186     {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
187     {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
188     {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
189     {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
190     {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
191     {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
192     {"sign_other", OPT_SIGN_OTHER, '<',
193      "Additional certificates to include in signed request"},
194     {"verify_other", OPT_VERIFY_OTHER, '<',
195      "Additional certificates to search for signer"},
196     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
197     {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
198     {"no-CAfile", OPT_NOCAFILE, '-',
199      "Do not load the default certificates file"},
200     {"no-CApath", OPT_NOCAPATH, '-',
201      "Do not load certificates from the default certificates directory"},
202     {"validity_period", OPT_VALIDITY_PERIOD, 'u',
203      "Maximum validity discrepancy in seconds"},
204     {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
205     {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
206     {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
207     {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
208     {"path", OPT_PATH, 's', "Path to use in OCSP request"},
209     {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
210     {"cert", OPT_CERT, '<', "Certificate to check"},
211     {"serial", OPT_SERIAL, 's', "Serial number to check"},
212     {"index", OPT_INDEX, '<', "Certificate status index file"},
213     {"CA", OPT_CA, '<', "CA certificate"},
214     {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
215     {"nrequest", OPT_REQUEST, 'p',
216      "Number of requests to accept (default unlimited)"},
217     {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
218     {"rsigner", OPT_RSIGNER, '<',
219      "Responder certificate to sign responses with"},
220     {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
221     {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
222     {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
223     {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
224     {"header", OPT_HEADER, 's', "key=value header to add"},
225     {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
226     {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
227     OPT_V_OPTIONS,
228     {NULL}
229 };
230
231 int ocsp_main(int argc, char **argv)
232 {
233     BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
234     const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
235     STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
236     int trailing_md = 0;
237     CA_DB *rdb = NULL;
238     EVP_PKEY *key = NULL, *rkey = NULL;
239     OCSP_BASICRESP *bs = NULL;
240     OCSP_REQUEST *req = NULL;
241     OCSP_RESPONSE *resp = NULL;
242     STACK_OF(CONF_VALUE) *headers = NULL;
243     STACK_OF(OCSP_CERTID) *ids = NULL;
244     STACK_OF(OPENSSL_STRING) *reqnames = NULL;
245     STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
246     STACK_OF(X509) *issuers = NULL;
247     X509 *issuer = NULL, *cert = NULL;
248     STACK_OF(X509) *rca_cert = NULL;
249     const EVP_MD *resp_certid_md = NULL;
250     X509 *signer = NULL, *rsigner = NULL;
251     X509_STORE *store = NULL;
252     X509_VERIFY_PARAM *vpm = NULL;
253     const char *CAfile = NULL, *CApath = NULL;
254     char *header, *value;
255     char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
256     char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
257     char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
258     char *rsignfile = NULL, *rkeyfile = NULL;
259     char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
260     char *signfile = NULL, *keyfile = NULL;
261     char *thost = NULL, *tport = NULL, *tpath = NULL;
262     int noCAfile = 0, noCApath = 0;
263     int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
264     int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
265     int req_text = 0, resp_text = 0, ret = 1;
266     int req_timeout = -1;
267     long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
268     unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
269     OPTION_CHOICE o;
270
271     reqnames = sk_OPENSSL_STRING_new_null();
272     if (reqnames == NULL)
273         goto end;
274     ids = sk_OCSP_CERTID_new_null();
275     if (ids == NULL)
276         goto end;
277     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
278         return 1;
279
280     prog = opt_init(argc, argv, ocsp_options);
281     while ((o = opt_next()) != OPT_EOF) {
282         switch (o) {
283         case OPT_EOF:
284         case OPT_ERR:
285  opthelp:
286             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
287             goto end;
288         case OPT_HELP:
289             ret = 0;
290             opt_help(ocsp_options);
291             goto end;
292         case OPT_OUTFILE:
293             outfile = opt_arg();
294             break;
295         case OPT_TIMEOUT:
296 #ifndef OPENSSL_NO_SOCK
297             req_timeout = atoi(opt_arg());
298 #endif
299             break;
300         case OPT_URL:
301             OPENSSL_free(thost);
302             OPENSSL_free(tport);
303             OPENSSL_free(tpath);
304             thost = tport = tpath = NULL;
305             if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
306                 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
307                 goto end;
308             }
309             thost = host;
310             tport = port;
311             tpath = path;
312             break;
313         case OPT_HOST:
314             host = opt_arg();
315             break;
316         case OPT_PORT:
317             port = opt_arg();
318             break;
319         case OPT_IGNORE_ERR:
320             ignore_err = 1;
321             break;
322         case OPT_NOVERIFY:
323             noverify = 1;
324             break;
325         case OPT_NONCE:
326             add_nonce = 2;
327             break;
328         case OPT_NO_NONCE:
329             add_nonce = 0;
330             break;
331         case OPT_RESP_NO_CERTS:
332             rflags |= OCSP_NOCERTS;
333             break;
334         case OPT_RESP_KEY_ID:
335             rflags |= OCSP_RESPID_KEY;
336             break;
337         case OPT_NO_CERTS:
338             sign_flags |= OCSP_NOCERTS;
339             break;
340         case OPT_NO_SIGNATURE_VERIFY:
341             verify_flags |= OCSP_NOSIGS;
342             break;
343         case OPT_NO_CERT_VERIFY:
344             verify_flags |= OCSP_NOVERIFY;
345             break;
346         case OPT_NO_CHAIN:
347             verify_flags |= OCSP_NOCHAIN;
348             break;
349         case OPT_NO_CERT_CHECKS:
350             verify_flags |= OCSP_NOCHECKS;
351             break;
352         case OPT_NO_EXPLICIT:
353             verify_flags |= OCSP_NOEXPLICIT;
354             break;
355         case OPT_TRUST_OTHER:
356             verify_flags |= OCSP_TRUSTOTHER;
357             break;
358         case OPT_NO_INTERN:
359             verify_flags |= OCSP_NOINTERN;
360             break;
361         case OPT_BADSIG:
362             badsig = 1;
363             break;
364         case OPT_TEXT:
365             req_text = resp_text = 1;
366             break;
367         case OPT_REQ_TEXT:
368             req_text = 1;
369             break;
370         case OPT_RESP_TEXT:
371             resp_text = 1;
372             break;
373         case OPT_REQIN:
374             reqin = opt_arg();
375             break;
376         case OPT_RESPIN:
377             respin = opt_arg();
378             break;
379         case OPT_SIGNER:
380             signfile = opt_arg();
381             break;
382         case OPT_VAFILE:
383             verify_certfile = opt_arg();
384             verify_flags |= OCSP_TRUSTOTHER;
385             break;
386         case OPT_SIGN_OTHER:
387             sign_certfile = opt_arg();
388             break;
389         case OPT_VERIFY_OTHER:
390             verify_certfile = opt_arg();
391             break;
392         case OPT_CAFILE:
393             CAfile = opt_arg();
394             break;
395         case OPT_CAPATH:
396             CApath = opt_arg();
397             break;
398         case OPT_NOCAFILE:
399             noCAfile = 1;
400             break;
401         case OPT_NOCAPATH:
402             noCApath = 1;
403             break;
404         case OPT_V_CASES:
405             if (!opt_verify(o, vpm))
406                 goto end;
407             vpmtouched++;
408             break;
409         case OPT_VALIDITY_PERIOD:
410             opt_long(opt_arg(), &nsec);
411             break;
412         case OPT_STATUS_AGE:
413             opt_long(opt_arg(), &maxage);
414             break;
415         case OPT_SIGNKEY:
416             keyfile = opt_arg();
417             break;
418         case OPT_REQOUT:
419             reqout = opt_arg();
420             break;
421         case OPT_RESPOUT:
422             respout = opt_arg();
423             break;
424         case OPT_PATH:
425             path = opt_arg();
426             break;
427         case OPT_ISSUER:
428             issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
429             if (issuer == NULL)
430                 goto end;
431             if (issuers == NULL) {
432                 if ((issuers = sk_X509_new_null()) == NULL)
433                     goto end;
434             }
435             sk_X509_push(issuers, issuer);
436             break;
437         case OPT_CERT:
438             X509_free(cert);
439             cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
440             if (cert == NULL)
441                 goto end;
442             if (cert_id_md == NULL)
443                 cert_id_md = EVP_sha1();
444             if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
445                 goto end;
446             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
447                 goto end;
448             trailing_md = 0;
449             break;
450         case OPT_SERIAL:
451             if (cert_id_md == NULL)
452                 cert_id_md = EVP_sha1();
453             if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
454                 goto end;
455             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
456                 goto end;
457             trailing_md = 0;
458             break;
459         case OPT_INDEX:
460             ridx_filename = opt_arg();
461             break;
462         case OPT_CA:
463             rca_filename = opt_arg();
464             break;
465         case OPT_NMIN:
466             opt_int(opt_arg(), &nmin);
467             if (ndays == -1)
468                 ndays = 0;
469             break;
470         case OPT_REQUEST:
471             opt_int(opt_arg(), &accept_count);
472             break;
473         case OPT_NDAYS:
474             ndays = atoi(opt_arg());
475             break;
476         case OPT_RSIGNER:
477             rsignfile = opt_arg();
478             break;
479         case OPT_RKEY:
480             rkeyfile = opt_arg();
481             break;
482         case OPT_ROTHER:
483             rcertfile = opt_arg();
484             break;
485         case OPT_RMD:   /* Response MessageDigest */
486             if (!opt_md(opt_arg(), &rsign_md))
487                 goto end;
488             break;
489         case OPT_RSIGOPT:
490             if (rsign_sigopts == NULL)
491                 rsign_sigopts = sk_OPENSSL_STRING_new_null();
492             if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
493                 goto end;
494             break;
495         case OPT_HEADER:
496             header = opt_arg();
497             value = strchr(header, '=');
498             if (value == NULL) {
499                 BIO_printf(bio_err, "Missing = in header key=value\n");
500                 goto opthelp;
501             }
502             *value++ = '\0';
503             if (!X509V3_add_value(header, value, &headers))
504                 goto end;
505             break;
506         case OPT_RCID:
507             resp_certid_md = EVP_get_digestbyname(opt_arg());
508             if (resp_certid_md == NULL)
509                 goto opthelp;
510             break;
511         case OPT_MD:
512             if (trailing_md) {
513                 BIO_printf(bio_err,
514                            "%s: Digest must be before -cert or -serial\n",
515                            prog);
516                 goto opthelp;
517             }
518             if (!opt_md(opt_unknown(), &cert_id_md))
519                 goto opthelp;
520             trailing_md = 1;
521             break;
522         case OPT_MULTI:
523 # ifdef OCSP_DAEMON
524             multi = atoi(opt_arg());
525 # endif
526             break;
527         }
528     }
529     if (trailing_md) {
530         BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
531                    prog);
532         goto opthelp;
533     }
534     argc = opt_num_rest();
535     if (argc != 0)
536         goto opthelp;
537
538     /* Have we anything to do? */
539     if (req == NULL && reqin == NULL
540         && respin == NULL && !(port != NULL && ridx_filename != NULL))
541         goto opthelp;
542
543     out = bio_open_default(outfile, 'w', FORMAT_TEXT);
544     if (out == NULL)
545         goto end;
546
547     if (req == NULL && (add_nonce != 2))
548         add_nonce = 0;
549
550     if (req == NULL && reqin != NULL) {
551         derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
552         if (derbio == NULL)
553             goto end;
554         req = d2i_OCSP_REQUEST_bio(derbio, NULL);
555         BIO_free(derbio);
556         if (req == NULL) {
557             BIO_printf(bio_err, "Error reading OCSP request\n");
558             goto end;
559         }
560     }
561
562     if (req == NULL && port != NULL) {
563         acbio = init_responder(port);
564         if (acbio == NULL)
565             goto end;
566     }
567
568     if (rsignfile != NULL) {
569         if (rkeyfile == NULL)
570             rkeyfile = rsignfile;
571         rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
572         if (rsigner == NULL) {
573             BIO_printf(bio_err, "Error loading responder certificate\n");
574             goto end;
575         }
576         if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
577                         NULL, "CA certificate"))
578             goto end;
579         if (rcertfile != NULL) {
580             if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
581                             "responder other certificates"))
582                 goto end;
583         }
584         rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, 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 OCSP_DAEMON
606     if (multi && acbio != NULL)
607         spawn_loop();
608     if (acbio != NULL && req_timeout > 0)
609         signal(SIGALRM, sock_timeout);
610 #endif
611
612     if (acbio != NULL)
613         log_message(LOG_INFO, "waiting for OCSP client connections...");
614
615 redo_accept:
616
617     if (acbio != NULL) {
618 # ifdef OCSP_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(LOG_ERR, "error reloading updated index: %s",
628                             ridx_filename);
629             }
630         }
631 # endif
632
633         req = NULL;
634         if (!do_responder(&req, &cbio, acbio, req_timeout))
635             goto redo_accept;
636
637         if (req == NULL) {
638             resp =
639                 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
640                                      NULL);
641             send_ocsp_response(cbio, resp);
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_PEM, "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, FORMAT_PEM, 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, CApath, noCAfile, noCApath);
769         if (!store)
770             goto end;
771     }
772     if (vpmtouched)
773         X509_STORE_set1_param(store, vpm);
774     if (verify_certfile != NULL) {
775         if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
776                         "validator certificate"))
777             goto end;
778     }
779
780     bs = OCSP_response_get1_basic(resp);
781     if (bs == NULL) {
782         BIO_printf(bio_err, "Error parsing response\n");
783         goto end;
784     }
785
786     ret = 0;
787
788     if (!noverify) {
789         if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
790             if (i == -1)
791                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
792             else {
793                 BIO_printf(bio_err, "Nonce Verify error\n");
794                 ret = 1;
795                 goto end;
796             }
797         }
798
799         i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
800         if (i <= 0 && issuers) {
801             i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
802             if (i > 0)
803                 ERR_clear_error();
804         }
805         if (i <= 0) {
806             BIO_printf(bio_err, "Response Verify Failure\n");
807             ERR_print_errors(bio_err);
808             ret = 1;
809         } else {
810             BIO_printf(bio_err, "Response verify OK\n");
811         }
812     }
813
814     print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
815
816  end:
817     ERR_print_errors(bio_err);
818     X509_free(signer);
819     X509_STORE_free(store);
820     X509_VERIFY_PARAM_free(vpm);
821     sk_OPENSSL_STRING_free(rsign_sigopts);
822     EVP_PKEY_free(key);
823     EVP_PKEY_free(rkey);
824     X509_free(cert);
825     sk_X509_pop_free(issuers, X509_free);
826     X509_free(rsigner);
827     sk_X509_pop_free(rca_cert, X509_free);
828     free_index(rdb);
829     BIO_free_all(cbio);
830     BIO_free_all(acbio);
831     BIO_free_all(out);
832     OCSP_REQUEST_free(req);
833     OCSP_RESPONSE_free(resp);
834     OCSP_BASICRESP_free(bs);
835     sk_OPENSSL_STRING_free(reqnames);
836     sk_OCSP_CERTID_free(ids);
837     sk_X509_pop_free(sign_other, X509_free);
838     sk_X509_pop_free(verify_other, X509_free);
839     sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
840     OPENSSL_free(thost);
841     OPENSSL_free(tport);
842     OPENSSL_free(tpath);
843
844     return ret;
845 }
846
847 static void
848 log_message(int level, const char *fmt, ...)
849 {
850     va_list ap;
851
852     va_start(ap, fmt);
853 # ifdef OCSP_DAEMON
854     if (multi) {
855         char buf[1024];
856         if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
857             syslog(level, "%s", buf);
858         }
859         if (level >= LOG_ERR)
860             ERR_print_errors_cb(print_syslog, &level);
861     }
862 # endif
863     if (!multi) {
864         BIO_printf(bio_err, "%s: ", prog);
865         BIO_vprintf(bio_err, fmt, ap);
866         BIO_printf(bio_err, "\n");
867     }
868     va_end(ap);
869 }
870
871 # ifdef OCSP_DAEMON
872
873 static int print_syslog(const char *str, size_t len, void *levPtr)
874 {
875     int level = *(int *)levPtr;
876     int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
877
878     syslog(level, "%.*s", ilen, str);
879
880     return ilen;
881 }
882
883 static int index_changed(CA_DB *rdb)
884 {
885     struct stat sb;
886
887     if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
888         if (rdb->dbst.st_mtime != sb.st_mtime
889             || rdb->dbst.st_ctime != sb.st_ctime
890             || rdb->dbst.st_ino != sb.st_ino
891             || rdb->dbst.st_dev != sb.st_dev) {
892             syslog(LOG_INFO, "index file changed, reloading");
893             return 1;
894         }
895     }
896     return 0;
897 }
898
899 static void killall(int ret, pid_t *kidpids)
900 {
901     int i;
902
903     for (i = 0; i < multi; ++i)
904         if (kidpids[i] != 0)
905             (void)kill(kidpids[i], SIGTERM);
906     OPENSSL_free(kidpids);
907     sleep(1);
908     exit(ret);
909 }
910
911 static int termsig = 0;
912
913 static void noteterm (int sig)
914 {
915     termsig = sig;
916 }
917
918 /*
919  * Loop spawning up to `multi` child processes, only child processes return
920  * from this function.  The parent process loops until receiving a termination
921  * signal, kills extant children and exits without returning.
922  */
923 static void spawn_loop(void)
924 {
925     pid_t *kidpids = NULL;
926     int status;
927     int procs = 0;
928     int i;
929
930     openlog(prog, LOG_PID, LOG_DAEMON);
931
932     if (setpgid(0, 0)) {
933         syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
934                strerror(errno));
935         exit(1);
936     }
937     kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
938     for (i = 0; i < multi; ++i)
939         kidpids[i] = 0;
940
941     signal(SIGINT, noteterm);
942     signal(SIGTERM, noteterm);
943
944     while (termsig == 0) {
945         pid_t fpid;
946
947         /*
948          * Wait for a child to replace when we're at the limit.
949          * Slow down if a child exited abnormally or waitpid() < 0
950          */
951         while (termsig == 0 && procs >= multi) {
952             if ((fpid = waitpid(-1, &status, 0)) > 0) {
953                 for (i = 0; i < procs; ++i) {
954                     if (kidpids[i] == fpid) {
955                         kidpids[i] = 0;
956                         --procs;
957                         break;
958                     }
959                 }
960                 if (i >= multi) {
961                     syslog(LOG_ERR, "fatal: internal error: "
962                            "no matching child slot for pid: %ld",
963                            (long) fpid);
964                     killall(1, kidpids);
965                 }
966                 if (status != 0) {
967                     if (WIFEXITED(status))
968                         syslog(LOG_WARNING, "child process: %ld, exit status: %d",
969                                (long)fpid, WEXITSTATUS(status));
970                     else if (WIFSIGNALED(status))
971                         syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
972                                (long)fpid, WTERMSIG(status),
973 #ifdef WCOREDUMP
974                                WCOREDUMP(status) ? " (core dumped)" :
975 #endif
976                                "");
977                     sleep(1);
978                 }
979                 break;
980             } else if (errno != EINTR) {
981                 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
982                 killall(1, kidpids);
983             }
984         }
985         if (termsig)
986             break;
987
988         switch(fpid = fork()) {
989         case -1:            /* error */
990             /* System critically low on memory, pause and try again later */
991             sleep(30);
992             break;
993         case 0:             /* child */
994             OPENSSL_free(kidpids);
995             signal(SIGINT, SIG_DFL);
996             signal(SIGTERM, SIG_DFL);
997             if (termsig)
998                 _exit(0);
999             if (RAND_poll() <= 0) {
1000                 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1001                 _exit(1);
1002             }
1003             return;
1004         default:            /* parent */
1005             for (i = 0; i < multi; ++i) {
1006                 if (kidpids[i] == 0) {
1007                     kidpids[i] = fpid;
1008                     procs++;
1009                     break;
1010                 }
1011             }
1012             if (i >= multi) {
1013                 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1014                 killall(1, kidpids);
1015             }
1016             break;
1017         }
1018     }
1019
1020     /* The loop above can only break on termsig */
1021     syslog(LOG_INFO, "terminating on signal: %d", termsig);
1022     killall(0, kidpids);
1023 }
1024 # endif
1025
1026 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1027                          const EVP_MD *cert_id_md, X509 *issuer,
1028                          STACK_OF(OCSP_CERTID) *ids)
1029 {
1030     OCSP_CERTID *id;
1031
1032     if (issuer == NULL) {
1033         BIO_printf(bio_err, "No issuer certificate specified\n");
1034         return 0;
1035     }
1036     if (*req == NULL)
1037         *req = OCSP_REQUEST_new();
1038     if (*req == NULL)
1039         goto err;
1040     id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1041     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1042         goto err;
1043     if (!OCSP_request_add0_id(*req, id))
1044         goto err;
1045     return 1;
1046
1047  err:
1048     BIO_printf(bio_err, "Error Creating OCSP request\n");
1049     return 0;
1050 }
1051
1052 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1053                            const EVP_MD *cert_id_md, X509 *issuer,
1054                            STACK_OF(OCSP_CERTID) *ids)
1055 {
1056     OCSP_CERTID *id;
1057     X509_NAME *iname;
1058     ASN1_BIT_STRING *ikey;
1059     ASN1_INTEGER *sno;
1060
1061     if (issuer == NULL) {
1062         BIO_printf(bio_err, "No issuer certificate specified\n");
1063         return 0;
1064     }
1065     if (*req == NULL)
1066         *req = OCSP_REQUEST_new();
1067     if (*req == NULL)
1068         goto err;
1069     iname = X509_get_subject_name(issuer);
1070     ikey = X509_get0_pubkey_bitstr(issuer);
1071     sno = s2i_ASN1_INTEGER(NULL, serial);
1072     if (sno == NULL) {
1073         BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1074         return 0;
1075     }
1076     id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1077     ASN1_INTEGER_free(sno);
1078     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1079         goto err;
1080     if (!OCSP_request_add0_id(*req, id))
1081         goto err;
1082     return 1;
1083
1084  err:
1085     BIO_printf(bio_err, "Error Creating OCSP request\n");
1086     return 0;
1087 }
1088
1089 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1090                               STACK_OF(OPENSSL_STRING) *names,
1091                               STACK_OF(OCSP_CERTID) *ids, long nsec,
1092                               long maxage)
1093 {
1094     OCSP_CERTID *id;
1095     const char *name;
1096     int i, status, reason;
1097     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1098
1099     if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1100         || !sk_OCSP_CERTID_num(ids))
1101         return;
1102
1103     for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1104         id = sk_OCSP_CERTID_value(ids, i);
1105         name = sk_OPENSSL_STRING_value(names, i);
1106         BIO_printf(out, "%s: ", name);
1107
1108         if (!OCSP_resp_find_status(bs, id, &status, &reason,
1109                                    &rev, &thisupd, &nextupd)) {
1110             BIO_puts(out, "ERROR: No Status found.\n");
1111             continue;
1112         }
1113
1114         /*
1115          * Check validity: if invalid write to output BIO so we know which
1116          * response this refers to.
1117          */
1118         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1119             BIO_puts(out, "WARNING: Status times invalid.\n");
1120             ERR_print_errors(out);
1121         }
1122         BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1123
1124         BIO_puts(out, "\tThis Update: ");
1125         ASN1_GENERALIZEDTIME_print(out, thisupd);
1126         BIO_puts(out, "\n");
1127
1128         if (nextupd) {
1129             BIO_puts(out, "\tNext Update: ");
1130             ASN1_GENERALIZEDTIME_print(out, nextupd);
1131             BIO_puts(out, "\n");
1132         }
1133
1134         if (status != V_OCSP_CERTSTATUS_REVOKED)
1135             continue;
1136
1137         if (reason != -1)
1138             BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1139
1140         BIO_puts(out, "\tRevocation Time: ");
1141         ASN1_GENERALIZEDTIME_print(out, rev);
1142         BIO_puts(out, "\n");
1143     }
1144 }
1145
1146 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1147                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1148                               EVP_PKEY *rkey, const EVP_MD *rmd,
1149                               STACK_OF(OPENSSL_STRING) *sigopts,
1150                               STACK_OF(X509) *rother, unsigned long flags,
1151                               int nmin, int ndays, int badsig,
1152                               const EVP_MD *resp_md)
1153 {
1154     ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1155     OCSP_CERTID *cid;
1156     OCSP_BASICRESP *bs = NULL;
1157     int i, id_count;
1158     EVP_MD_CTX *mctx = NULL;
1159     EVP_PKEY_CTX *pkctx = NULL;
1160
1161     id_count = OCSP_request_onereq_count(req);
1162
1163     if (id_count <= 0) {
1164         *resp =
1165             OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1166         goto end;
1167     }
1168
1169     bs = OCSP_BASICRESP_new();
1170     thisupd = X509_gmtime_adj(NULL, 0);
1171     if (ndays != -1)
1172         nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1173
1174     /* Examine each certificate id in the request */
1175     for (i = 0; i < id_count; i++) {
1176         OCSP_ONEREQ *one;
1177         ASN1_INTEGER *serial;
1178         char **inf;
1179         int jj;
1180         int found = 0;
1181         ASN1_OBJECT *cert_id_md_oid;
1182         const EVP_MD *cert_id_md;
1183         OCSP_CERTID *cid_resp_md = NULL;
1184
1185         one = OCSP_request_onereq_get0(req, i);
1186         cid = OCSP_onereq_get0_id(one);
1187
1188         OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1189
1190         cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1191         if (cert_id_md == NULL) {
1192             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1193                                          NULL);
1194             goto end;
1195         }
1196         for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1197             X509 *ca_cert = sk_X509_value(ca, jj);
1198             OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1199
1200             if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1201                 found = 1;
1202                 if (resp_md != NULL)
1203                     cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1204             }
1205             OCSP_CERTID_free(ca_id);
1206         }
1207         OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1208         inf = lookup_serial(db, serial);
1209
1210         /* at this point, we can have cid be an alias of cid_resp_md */
1211         cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1212
1213         if (!found) {
1214             OCSP_basic_add1_status(bs, cid,
1215                                    V_OCSP_CERTSTATUS_UNKNOWN,
1216                                    0, NULL, thisupd, nextupd);
1217             continue;
1218         }
1219         if (inf == NULL) {
1220             OCSP_basic_add1_status(bs, cid,
1221                                    V_OCSP_CERTSTATUS_UNKNOWN,
1222                                    0, NULL, thisupd, nextupd);
1223         } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1224             OCSP_basic_add1_status(bs, cid,
1225                                    V_OCSP_CERTSTATUS_GOOD,
1226                                    0, NULL, thisupd, nextupd);
1227         } else if (inf[DB_type][0] == DB_TYPE_REV) {
1228             ASN1_OBJECT *inst = NULL;
1229             ASN1_TIME *revtm = NULL;
1230             ASN1_GENERALIZEDTIME *invtm = NULL;
1231             OCSP_SINGLERESP *single;
1232             int reason = -1;
1233
1234             unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1235             single = OCSP_basic_add1_status(bs, cid,
1236                                             V_OCSP_CERTSTATUS_REVOKED,
1237                                             reason, revtm, thisupd, nextupd);
1238             if (invtm != NULL)
1239                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1240                                              invtm, 0, 0);
1241             else if (inst != NULL)
1242                 OCSP_SINGLERESP_add1_ext_i2d(single,
1243                                              NID_hold_instruction_code, inst,
1244                                              0, 0);
1245             ASN1_OBJECT_free(inst);
1246             ASN1_TIME_free(revtm);
1247             ASN1_GENERALIZEDTIME_free(invtm);
1248         }
1249         OCSP_CERTID_free(cid_resp_md);
1250     }
1251
1252     OCSP_copy_nonce(bs, req);
1253
1254     mctx = EVP_MD_CTX_new();
1255     if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1256         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1257         goto end;
1258     }
1259     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1260         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1261
1262         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1263             BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1264             ERR_print_errors(bio_err);
1265             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1266                                          NULL);
1267             goto end;
1268         }
1269     }
1270     if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1271         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1272         goto end;
1273     }
1274
1275     if (badsig) {
1276         const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1277         corrupt_signature(sig);
1278     }
1279
1280     *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1281
1282  end:
1283     EVP_MD_CTX_free(mctx);
1284     ASN1_TIME_free(thisupd);
1285     ASN1_TIME_free(nextupd);
1286     OCSP_BASICRESP_free(bs);
1287 }
1288
1289 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1290 {
1291     int i;
1292     BIGNUM *bn = NULL;
1293     char *itmp, *row[DB_NUMBER], **rrow;
1294     for (i = 0; i < DB_NUMBER; i++)
1295         row[i] = NULL;
1296     bn = ASN1_INTEGER_to_BN(ser, NULL);
1297     OPENSSL_assert(bn);         /* FIXME: should report an error at this
1298                                  * point and abort */
1299     if (BN_is_zero(bn))
1300         itmp = OPENSSL_strdup("00");
1301     else
1302         itmp = BN_bn2hex(bn);
1303     row[DB_serial] = itmp;
1304     BN_free(bn);
1305     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1306     OPENSSL_free(itmp);
1307     return rrow;
1308 }
1309
1310 /* Quick and dirty OCSP server: read in and parse input request */
1311
1312 static BIO *init_responder(const char *port)
1313 {
1314 # ifdef OPENSSL_NO_SOCK
1315     BIO_printf(bio_err,
1316                "Error setting up accept BIO - sockets not supported.\n");
1317     return NULL;
1318 # else
1319     BIO *acbio = NULL, *bufbio = NULL;
1320
1321     bufbio = BIO_new(BIO_f_buffer());
1322     if (bufbio == NULL)
1323         goto err;
1324     acbio = BIO_new(BIO_s_accept());
1325     if (acbio == NULL
1326         || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1327         || BIO_set_accept_port(acbio, port) < 0) {
1328         log_message(LOG_ERR, "Error setting up accept BIO");
1329         goto err;
1330     }
1331
1332     BIO_set_accept_bios(acbio, bufbio);
1333     bufbio = NULL;
1334     if (BIO_do_accept(acbio) <= 0) {
1335         log_message(LOG_ERR, "Error starting accept");
1336         goto err;
1337     }
1338
1339     return acbio;
1340
1341  err:
1342     BIO_free_all(acbio);
1343     BIO_free(bufbio);
1344     return NULL;
1345 # endif
1346 }
1347
1348 # ifndef OPENSSL_NO_SOCK
1349 /*
1350  * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1351  */
1352 static int urldecode(char *p)
1353 {
1354     unsigned char *out = (unsigned char *)p;
1355     unsigned char *save = out;
1356
1357     for (; *p; p++) {
1358         if (*p != '%')
1359             *out++ = *p;
1360         else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1361             /* Don't check, can't fail because of ixdigit() call. */
1362             *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1363                    | OPENSSL_hexchar2int(p[2]);
1364             p += 2;
1365         }
1366         else
1367             return -1;
1368     }
1369     *out = '\0';
1370     return (int)(out - save);
1371 }
1372 # endif
1373
1374 # ifdef OCSP_DAEMON
1375 static void sock_timeout(int signum)
1376 {
1377     if (acfd != (int)INVALID_SOCKET)
1378         (void)shutdown(acfd, SHUT_RD);
1379 }
1380 # endif
1381
1382 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1383                         int timeout)
1384 {
1385 # ifdef OPENSSL_NO_SOCK
1386     return 0;
1387 # else
1388     int len;
1389     OCSP_REQUEST *req = NULL;
1390     char inbuf[2048], reqbuf[2048];
1391     char *p, *q;
1392     BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1393     const char *client;
1394
1395     *preq = NULL;
1396
1397     /* Connection loss before accept() is routine, ignore silently */
1398     if (BIO_do_accept(acbio) <= 0)
1399         return 0;
1400
1401     cbio = BIO_pop(acbio);
1402     *pcbio = cbio;
1403     client = BIO_get_peer_name(cbio);
1404
1405 #  ifdef OCSP_DAEMON
1406     if (timeout > 0) {
1407         (void) BIO_get_fd(cbio, &acfd);
1408         alarm(timeout);
1409     }
1410 #  endif
1411
1412     /* Read the request line. */
1413     len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1414     if (len <= 0)
1415         goto out;
1416
1417     if (strncmp(reqbuf, "GET ", 4) == 0) {
1418         /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1419         for (p = reqbuf + 4; *p == ' '; ++p)
1420             continue;
1421         if (*p != '/') {
1422             log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1423             goto out;
1424         }
1425         p++;
1426
1427         /* Splice off the HTTP version identifier. */
1428         for (q = p; *q; q++)
1429             if (*q == ' ')
1430                 break;
1431         if (strncmp(q, " HTTP/1.", 8) != 0) {
1432             log_message(LOG_INFO,
1433                         "Invalid request -- bad HTTP version: %s", client);
1434             goto out;
1435         }
1436         *q = '\0';
1437
1438         /*
1439          * Skip "GET / HTTP..." requests often used by load-balancers
1440          */
1441         if (p[1] == '\0')
1442             goto out;
1443
1444         len = urldecode(p);
1445         if (len <= 0) {
1446             log_message(LOG_INFO,
1447                         "Invalid request -- bad URL encoding: %s", client);
1448             goto out;
1449         }
1450         if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1451             || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1452             log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1453             goto out;
1454         }
1455         BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1456         getbio = BIO_push(b64, getbio);
1457     } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1458         log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1459         goto out;
1460     }
1461
1462     /* Read and skip past the headers. */
1463     for (;;) {
1464         len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1465         if (len <= 0)
1466             goto out;
1467         if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1468             break;
1469     }
1470
1471 #  ifdef OCSP_DAEMON
1472     /* Clear alarm before we close the client socket */
1473     alarm(0);
1474     timeout = 0;
1475 #  endif
1476
1477     /* Try to read OCSP request */
1478     if (getbio != NULL) {
1479         req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1480         BIO_free_all(getbio);
1481     } else {
1482         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1483     }
1484
1485     if (req == NULL)
1486         log_message(LOG_ERR, "Error parsing OCSP request");
1487
1488     *preq = req;
1489
1490 out:
1491 #  ifdef OCSP_DAEMON
1492     if (timeout > 0)
1493         alarm(0);
1494     acfd = (int)INVALID_SOCKET;
1495 #  endif
1496     return 1;
1497 # endif
1498 }
1499
1500 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1501 {
1502     char http_resp[] =
1503         "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1504         "Content-Length: %d\r\n\r\n";
1505     if (cbio == NULL)
1506         return 0;
1507     BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1508     i2d_OCSP_RESPONSE_bio(cbio, resp);
1509     (void)BIO_flush(cbio);
1510     return 1;
1511 }
1512
1513 # ifndef OPENSSL_NO_SOCK
1514 static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host,
1515                                       const char *path,
1516                                       const STACK_OF(CONF_VALUE) *headers,
1517                                       OCSP_REQUEST *req, int req_timeout)
1518 {
1519     int fd;
1520     int rv;
1521     int i;
1522     int add_host = 1;
1523     OCSP_REQ_CTX *ctx = NULL;
1524     OCSP_RESPONSE *rsp = NULL;
1525     fd_set confds;
1526     struct timeval tv;
1527
1528     if (req_timeout != -1)
1529         BIO_set_nbio(cbio, 1);
1530
1531     rv = BIO_do_connect(cbio);
1532
1533     if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio))) {
1534         BIO_puts(bio_err, "Error connecting BIO\n");
1535         return NULL;
1536     }
1537
1538     if (BIO_get_fd(cbio, &fd) < 0) {
1539         BIO_puts(bio_err, "Can't get connection fd\n");
1540         goto err;
1541     }
1542
1543     if (req_timeout != -1 && rv <= 0) {
1544         FD_ZERO(&confds);
1545         openssl_fdset(fd, &confds);
1546         tv.tv_usec = 0;
1547         tv.tv_sec = req_timeout;
1548         rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1549         if (rv == 0) {
1550             BIO_puts(bio_err, "Timeout on connect\n");
1551             return NULL;
1552         }
1553     }
1554
1555     ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1556     if (ctx == NULL)
1557         return NULL;
1558
1559     for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
1560         CONF_VALUE *hdr = sk_CONF_VALUE_value(headers, i);
1561         if (add_host == 1 && strcasecmp("host", hdr->name) == 0)
1562             add_host = 0;
1563         if (!OCSP_REQ_CTX_add1_header(ctx, hdr->name, hdr->value))
1564             goto err;
1565     }
1566
1567     if (add_host == 1 && OCSP_REQ_CTX_add1_header(ctx, "Host", host) == 0)
1568         goto err;
1569
1570     if (!OCSP_REQ_CTX_set1_req(ctx, req))
1571         goto err;
1572
1573     for (;;) {
1574         rv = OCSP_sendreq_nbio(&rsp, ctx);
1575         if (rv != -1)
1576             break;
1577         if (req_timeout == -1)
1578             continue;
1579         FD_ZERO(&confds);
1580         openssl_fdset(fd, &confds);
1581         tv.tv_usec = 0;
1582         tv.tv_sec = req_timeout;
1583         if (BIO_should_read(cbio)) {
1584             rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1585         } else if (BIO_should_write(cbio)) {
1586             rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1587         } else {
1588             BIO_puts(bio_err, "Unexpected retry condition\n");
1589             goto err;
1590         }
1591         if (rv == 0) {
1592             BIO_puts(bio_err, "Timeout on request\n");
1593             break;
1594         }
1595         if (rv == -1) {
1596             BIO_puts(bio_err, "Select error\n");
1597             break;
1598         }
1599
1600     }
1601  err:
1602     OCSP_REQ_CTX_free(ctx);
1603
1604     return rsp;
1605 }
1606
1607 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1608                                  const char *host, const char *path,
1609                                  const char *port, int use_ssl,
1610                                  STACK_OF(CONF_VALUE) *headers,
1611                                  int req_timeout)
1612 {
1613     BIO *cbio = NULL;
1614     SSL_CTX *ctx = NULL;
1615     OCSP_RESPONSE *resp = NULL;
1616
1617     cbio = BIO_new_connect(host);
1618     if (cbio == NULL) {
1619         BIO_printf(bio_err, "Error creating connect BIO\n");
1620         goto end;
1621     }
1622     if (port != NULL)
1623         BIO_set_conn_port(cbio, port);
1624     if (use_ssl == 1) {
1625         BIO *sbio;
1626         ctx = SSL_CTX_new(TLS_client_method());
1627         if (ctx == NULL) {
1628             BIO_printf(bio_err, "Error creating SSL context.\n");
1629             goto end;
1630         }
1631         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1632         sbio = BIO_new_ssl(ctx, 1);
1633         cbio = BIO_push(sbio, cbio);
1634     }
1635
1636     resp = query_responder(cbio, host, path, headers, req, req_timeout);
1637     if (resp == NULL)
1638         BIO_printf(bio_err, "Error querying OCSP responder\n");
1639  end:
1640     BIO_free_all(cbio);
1641     SSL_CTX_free(ctx);
1642     return resp;
1643 }
1644 # endif
1645
1646 #endif