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